Alex Rivera | Logout

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

Asked 2011-11-22T07:06:03.447
29

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]);
Edit
Report

1 Answer

-2

if you want an ArrayList you can use reflection to cheat

ArrayList<T> myList = new ArrayList<T>(numEls);
Field f = ArrayList.class.getField("size");//cache this
f.setAccessible(true);
f.setInt(myList, numEls);
answered 2011-11-22T10:50:44.163

Your Answer