javalistinitialization

Initializing List<T> with given number of nulls without loop?


Can a List<T> be initialized to contain a given number of nulls, where T is a type parameter of the class of which the list is a member? I sure can do it with a loop, but like to know whether it is possible without.

List<T> myList = new ArrayList<T>(numEls);

creates a list of the given capacity, but size 0, so myList.get(x) fails for all x, and so does, e.g. myList.set(numEls-1,null).

myList = Arrays.asList(new T[numEls]);

does not compile, and

 myList = (List<T>) Arrays.asList(new Object[numEls]);

compiles in Eclipse (with an Unchecked cast warning), but not with javac.


Update: Thank you for the answers! However, I found another, quite short, solution close to my last attempt above, which compiles both in eclipse and with our automated build system: Cast the array, not the list!

myList = Arrays.asList((T[]) new Object[numEls]);

Solution

  • If you don't need to mutate the list...

    List<T> result = Collections.nCopies(num, (T) null);
    

    ... or alternately

    List<T> result = new ArrayList<T>(Collections.nCopies(num, (T) null));