Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList.toArray() not converting to the correct type?

Tags:

java

arraylist

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?

like image 557
wassup Avatar asked Dec 03 '25 19:12

wassup


1 Answers

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.

like image 59
NPE Avatar answered Dec 06 '25 08:12

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!