A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
Register / Login
Win a copy of
The Mikado Method
this week in the
Agile and other Processes
forum!
JavaRanch
»
Java Forums
»
Certification
»
Programmer Certification (SCJP/OCPJP)
Author
toArray() question
Charith Fernando
Ranch Hand
Joined: Sep 12, 2005
Posts: 67
posted
Oct 22, 2006 23:30:00
0
hi,
i have seen code segments which uses the toArray() in different ways... just want to know the best mechanism and the difference...
(1)
List list = new ArrayList() String[] array = (String[])list.toArrray(new String[0]);
(2)
List list = new ArrayList() String[] array = (String[])list.toArrray(new String[list.size()]);
please note that this is in Java 1.4 in Java 5 we dont need the cast if we have a list which will only contain Strings...
Thank you
Charith
Charith I Fernando<br />SCJP5, SCWCD, SCBCD, BSc(Hons) IS<br />+94 773 263 222 (mobile)
wise owen
Ranch Hand
Joined: Feb 02, 2006
Posts: 2023
posted
Oct 23, 2006 04:06:00
0
//ArrayList.java public Object[] toArray(Object[] a) { if (a.length < size) a = (Object[]) Array.newInstance(a.getClass().getComponentType(), size); else if (a.length > size) a[size] = null; System.arraycopy(data, 0, a, 0, size); return a; }
If the passed array is large enough to contain the values to be returned, the method returns the passed array reference (that now contains the values to be returned) and not a newly created one.
[ October 23, 2006: Message edited by: wise owen ]
I agree. Here's the link:
http://zeroturnaround.com/jrebel
- it saves me about five hours per week
subject: toArray() question
Similar Threads
toArray(new String[0])
Doubt in toArray() method
Collection toArray( T[ ] ) method
dragdrop-colections
Using Lists and converting them to arrays problem
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter