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:
The reason your original version doesn’t work is that
toArray()returnsObject[]and notThing[]. You need to use the other form oftoArray—toArray(T[])— to get an array ofThings.