Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toArray() Problem?

 
Soumya Ranjan Mohanty
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

As the size of array s1 is 2 but after toArray() when the list test is copied into s1 array, it grows dynamically to hold 4 elements. How is it Possible? since array is of fixed size(i.e 2 here).
 
Himanshu Mall
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Soumya

Please read the Java Doc API toArray(Object[] a) and let us know what you missed.



 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hope, you know that, there are two flavor of toArray() method,
1) Returning Object type of array, filled with the list elements. {Object[] toArray()}
2) Generic type of toArray() method, which returns the Array of type T(like your toArray() method). {<T> T[] toArray(T[] a)}

If the given array is big enough, the elements are stored in this array. If there is room to spare in the array, that is, the length of the array is greater than the number of elements in the collection, the spare room is filled with null values before the array is returned. If the array is too small(like your case), a new array of type T and appropriate size is created. If T is not a supertype of the runtime type of every element in the collection, an ArrayStoreException is thrown.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic