This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes toArray() Problem? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "toArray() Problem?" Watch "toArray() Problem?" New topic

toArray() Problem?

Soumya Ranjan Mohanty
Ranch Hand

Joined: Mar 07, 2010
Posts: 44

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

Joined: Jun 28, 2010
Posts: 22

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

Himanshu Mall
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

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.

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
I agree. Here's the link:
subject: toArray() Problem?
jQuery in Action, 3rd edition