Categories

Java list litterals

I was recently deploring the lack of a list litteral in Java. It turns out that since Java 1.5, thanks to Java generics, variable length argument lists, and static import, one can get a rather good list litteral :

import junit.framework.TestCase;
import java.util.List;
import static java.util.Arrays.asList;
public class LiteralsTest extends TestCase {
     public void testList1() {
         List<String> list1P = asList("Hello","this","is","a","test");
         assertEquals("Hello",list1P.get(0));
         assertEquals("this",list1P.get(1));
         assertEquals("is",list1P.get(2));
         assertEquals("a",list1P.get(3));
         assertEquals("test",list1P.get(4));
     }
     public void testList2() {
         List<Integer> list1P = asList(3,2,1);
         // intValue needs to be used to disambiguate the call
         assertEquals(3,list1P.get(0).intValue());
         assertEquals(2,list1P.get(1).intValue());
         assertEquals(1,list1P.get(2).intValue());
     }
 }

The name could be a bit better, so it’s just a matter of building an alias :

public final class Literals {
     public static <T> List<T> list(T... itemsP) {
         return Arrays.asList(itemsP);
     }
 }

Or even, if you want the list to be mutable (Python-style) :

public final class Literals {
     public static <T> List<T> list(T... itemsP) {
         return new ArrayList<T>(Arrays.asList(itemsP));
     }
}

A whole new bag of tricks is opening…