Java – ClassCastException when eclipse “fixed” the code

eclipseexceptionjava

I get a ClassCastException when eclipse suggested that my code should be like that..

I have a class named Kort.

ArrayList<Kort> kort = new ArrayList<Kort>();

then I use toArray(), and eclipse suggest it should look like: Kort[] array = (Kort[])kort.toArray();

But it gives me this exception: ClassCastException ! 🙁

Best Answer

My suggestion is:

kort.toArray(new Kort[0])

Technically this might be fractionally slower than giving the correct size. However, you don't need to mention the collection variable name twice, so less chance of making a mistake. It's also easier to read. As a bonus, it also works with concurrent collections, where calling size doesn't really make a great deal of sense.

However, the best approach is to avoid using arrays of references if you possibly can.