0

I have a function that gets as parameter an indefinite number of ImageButtons.

private void addButtons(ImageButton... ib) {
// ...
}

So this is perfect if I want to call it for example this way:

addButtons(button1, button2, button3);

But now it happens to me that I have to use as a parameter an unknown number of objects, for example an array. Inside addButtons the ImageButton parameters are used as an array, so I tried this:

ArrayList<ImageButton> ibs = new ArrayList<ImageButton>();
// feed the ibs ArrayList
addButtons((ImageButton[])ibs.toArray());

And I get a ClassCastException.

Why?

0

3 Answers 3

5

Actually the method toArray() returns an Object[]

You have to use the overloaded method toArray(T[])

You should use :

addButtons(ibs.toArray(new ImageButton[ibs.size()]));
Sign up to request clarification or add additional context in comments.

8 Comments

You mean: ibs.toArray(new ImageButton[ibs.size()]))
ZouZou on Android I cannot find toArray(int x), there's not such a function.
Thank you, it works!!! I use it. I still don't understand why, anyway: it clearly states that it's not necessary to specify the array: "Returns an array containing all elements contained in this ArrayList. If the specified array is large enough to hold the elements, the specified array is used, otherwise an array of the same type is created."
@Beppi's toArray() returns Object[] but toArray(new ImageButton[...]) returns ImageButton[], and addButtons expects ImageButton[]
|
1

Use the overloaded toArray() method where you can specify the array type.

addButtons(ibs.toArray(new ImageButton[0]));

You can specify the size if you want to. If you don't, the method will simply create a bigger array before adding the elements.

1 Comment

That's smart. I don't need to specify the size.
1

Due to type erasure, a generic collection cannot create a strongly typed array unless you help it out:

addButtons(ibs.toArray(new ImageButton[ibs.size()]));

Unless you pass it an array of the correct type, it can only return an Object[].

3 Comments

Just being pedantic.... the Array-type has nothing to do withgenerics and erasure. This was true before that: docs.oracle.com/javase/1.4.2/docs/api/java/util/…
@rolfl: Yes, but that's more expected. You would expect a generic collection to be able to do this (like C# can)
That is true (it is counter-intuitive that it does not work without the assistance - with erasure the 'intuitive' information is gone though...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.