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?
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)
stream() would end up creating objects which are thrown away..toArray(new AnotherClass[size])size() might not be trivial for all types of List. I used to evaluate size everywhere but have switched my toArray conversions to use new T[0]new AnotherClass[0]. It’s robust and more efficient. If you want the full story, read shipilev.net/blog/2016/arrays-wisdom-ancients
[]. Since arrays are fixed-size, this is an array that contains nothing (and never can contain anything). This is a common sentinel value in calling#toArrayin which the method will make its own array to returntoArraymethod if you don't know the exact length.toArraywill then create a new array with the correct length and type. Since Java 11 this is no longer necessary as you can simply usesomeList.toArray(AnotherClass[]::new);List.toArray<T[]>java.util.Collectionand it is documented:The default implementation calls the generator function with zero and then passes the resulting array to toArray(T[]).docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/…. What a nonsense and waste of CPU cycles...ArrayListhas been proven the most efficient method since Java 6. Performance in managed environments with JIT and Hotspot optimizer can heavily contradict intuition. Besides that, it’s the only way for adefaultmethod to provide the necessary implementation guarantees for arbitrary implementations, like concurrent collections, for example. Passing a sized array would break for concurrent collections and be less efficient at the same time.