Aug 06
J Yu pointed out that, thanks to JDK 1.5, generics, and varargs, we now have a really nice way to simply create a List of stuff:
Was:
List list = new java.util.ArrayList();
list.add( “Rod” ); list.add( “James” ); list.add( “Chris” );
1.5:
List list = Arrays.asList(”Rod”, “James”, “Chris”);
or, with generics:
List
list = Arrays.asList(”Rod”, “James”, “Chris”);
Arrays.asList(..) was always around, but it changed from:
public static List asList(Object a)
to the nicer, if more cryptic:
public static <T> List<T> asList(T… a)
August 6th, 2004 at 5:15 pm
Or maybe:
List<String> list = Arrays.asList<String>(”Rod”, “James”, “Chris”);
I hope I got that right… haven’t messed with generic functions in 1.5, and I don’t have 1.5 at hand to try it out :-)
And yes, I still call it “1.5″.
August 6th, 2004 at 5:28 pm
There is still a lot to learn about java.util package.
Dion is copying a collection example from James Groovy presentation:
List list = new java.util.ArrayList();
list.add( “Rod” ); list.add( “James” ); list.add( “Chris” );
In the contexts where James used it it is probably does not matters
August 6th, 2004 at 5:34 pm
That is freaking out for me on 1.5 (build 1.5.0-beta-b32c).
It is happy with:
List list = Arrays.asList(new String[] {”Rod”, “James”, “Chris”});
but some reason it isn’t liking the varargs case.
AsListTest.java:10: asList(T[]) in java.util.Arrays cannot be applied to (jav
a.lang.String,java.lang.String,java.lang.String); no instance(s) of type variabl
e(s) T exist so that argument type java.lang.String conforms to formal parameter
type T[]
List list = Arrays.asList(”Rod”, “James”, “Chris”);
D
August 6th, 2004 at 7:29 pm
I had my JAVA_HOME pointing to the first beta (duh). It works like a charm on beta2.
Thanks.