Question on an Intellij 7.0 M2 code fix suggestion

This is the original line of code:
(SomeArray[]) someCollection.toArray(new SomeArray[0])

Intellij recommends to change it to:
(SomeArray[]) someCollection.toArray(new SomeArray[someCollection.size()])

The explanation given is to avoid heavy taxing on the JVM because of reflection. But the original way I have it, how is that using reflection? I am specifically saying create the array with size of 0 specifically. My question is isnt the first way of writing the code the same as the second way but perhaps even better?

4 comments
Comment actions Permalink

Hello Surya,

This is the original line of code:
(SomeArray[]) someCollection.toArray(new SomeArray[0])
Intellij recommends to change it to:
(SomeArray[]) someCollection.toArray(new
SomeArray[someCollection.size()])
The explanation given is to avoid heavy taxing on the JVM because of
reflection. But the original way I have it, how is that using
reflection? I am specifically saying create the array with size of 0
specifically. My question is isnt the first way of writing the code
the same as the second way but perhaps even better?


The array of size 0 that you pass in the first option is not enough to hold
the contents of your collection, so the toArray() method discards it and
creates a new one through reflection. In the second option, the array you
pass is used directly, and no extra allocation happens.

--
Dmitry Jemerov
Software Developer
JetBrains, Inc.
http://www.jetbrains.com/
"Develop with Pleasure!"


0
Comment actions Permalink

Thank you! That makes sense to me.

Just a clarification when you mean that no extra allocation happens what do you mean exactly? I am telling it instead of using something of size 0 use something that could be of size 100. Are you saying the JVM wont use up that 100 chunk of memory then until necessary?

Message was edited by:
Surya

0
Comment actions Permalink

"no extra allocation happens" means new SomeArray[someCollection.size()] will be used as-is for storing collection's elements and will be returned by toArray() method. Not JVM but toArray() method will use an array specified (the one you've created when called it) right away for storing collection's elements.

0
Comment actions Permalink

this is from ArrayList#toArray javadoc

If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

see http://www.docjar.com/docs/api/java/util/ArrayList.html#toArray(java.lang.Object[])

0

Please sign in to leave a comment.