So, what I got is:
class BlahBlah
{
public BlahBlah()
{
things = new ArrayList<Thing>();
}
public Thing[] getThings()
{
return (Thing[]) things.toArray();
}
private ArrayList<Thing> things;
}
In the other class I got:
for (Thing thing : someInstanceOfBlahBlah.getThings())
{
// some irrelevant code
}
And the error is:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LsomePackage.Thing;
at somePackage.Blahblah.getThings(Blahblah.java:10)
How can I solve this problem?
Try:
public Thing[] getThings()
{
return things.toArray(new Thing[things.size()]);
}
The reason your original version doesn't work is that toArray() returns Object[] and not Thing[]. You need to use the other form of toArray -- toArray(T[]) -- to get an array of Things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With