Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 0 mean in someList.toArray(new AnotherClass[0])?

In Java we have toArray() method which will return Object[]. If I want to return another data type I need to pass it to parameters like this

SomeClass.SomeList.toArray(new AnotherClass[0]);

What does 0 mean in this case?

like image 903
JustDreaming Avatar asked Dec 13 '25 03:12

JustDreaming


1 Answers

new AnotherClass[0] will create an array with 0 elements.

SomeList.toArray(...) will first check if the array is big enough to fit the elements and will create a new array of the desired size if it is not large enough.

You might prefer to do someList.toArray(new AnotherClass[someList.size()])

This way you don't create a zero element array and then throw it away.

But as @Rogue suggested, this does not perform better than new AnotherClass[0] (see https://shipilev.net/blog/2016/arrays-wisdom-ancients)

like image 160
lance-java Avatar answered Dec 15 '25 17:12

lance-java