Code Example: List.toArray(T[] a)

Most of the time, I write small code snippets and wrap them in a small test case to test my assumptions before I put them in a real places. For long a time, I wanted to capture these code snippets some where with my observations. Suddenly I realized, I could blog them too. I hope to continue this practice, but I am not very positive though :-)

Coming to my code snippet, I need to convert a List into an array and I saw java.util.List's " T[] toArray(T[] a)" fitting my bill. This syntax didn't really looked natural to me and I wrote this test case.

import java.util.ArrayList;
public class ToArray {
public static void main(String args[]) {
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
Integer[] ints = list.toArray(new Integer[]{});
for (Integer i : ints) {
System.out.println(i);
}
}
}

Output of theabove code snippet is:
$ java ToArray
1
2
3

I was bit confused whether the parameter to the toArray should be the same array
Integer[] ints = {};
ints = list.toArray(ints);
or any array of the same type
Integer[] ints = list.toArray(new Integer[]{});

Both of the above two works and what matters is only is the only type.

Comments:

From Javadoc of List.toArray(T[]) (http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html#toArray(T[]), we have, a - the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Posted by A. Sundararajan on March 06, 2007 at 09:49 AM IST #

Sorry, I conviniently ignored reading parameter part of the java doc. Never realized that the parameter is a IN/OUT parameter. Can you point me another API method example in which an array is IN/OUT parameter and the method returns an array.

Posted by Sankar on March 06, 2007 at 04:03 PM IST #

Post a Comment:
  • HTML Syntax: NOT allowed
About

bsankararao

Search

Categories
Archives
« May 2015
SunMonTueWedThuFriSat
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
      
Today