Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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]);
like image 543
arne.b Avatar asked Nov 22 '11 07:11

arne.b


People also ask

Can we initialize list as null in Java?

You should ideally decide based on your application logic whether to keep this list as empty or null. One disadvantage with null is that in the places where you are not expecting this list as null, you have to add extra null checks in the application code. One better way is to initialize your list using Collections.

Can we store null values in ArrayList?

Solution. Yes, We can insert null values to a list easily using its add() method.


3 Answers

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)); 
like image 141
Louis Wasserman Avatar answered Sep 30 '22 20:09

Louis Wasserman


You would need to use reflection to instantiate a backing array T[] using Array.newInstance():

public static <T> List<T> getListWithNulls(Class<T> componentType, int length) {
   T[] array = (T[])Array.newInstance(componentType, length);
   return new ArrayList<T>(Arrays.asList(array));
}

As you can see, this requires a reference to the Class<T> object representing the type of T:

List<String> strListWithNulls = getListWithNulls(String.class, 100);

Also make sure not to confuse the classes java.lang.reflect.Array and java.util.Arrays which are both used here.

Finally, note that reflection is going to be much slower than just using a loop.

like image 26
Paul Bellora Avatar answered Sep 30 '22 19:09

Paul Bellora


Not really a solution, but you wanted to avoid a loop.

void fillNullList(List<T> list, count) {
   if (count > 0) {
       list.add(null);
       fillNullList(list, count - 1);
   }
}

Seriously, why do you want to avoid a loop? Probably, you want a solution with O(1) complexity and not a O(n) complexity solution regardless if a loop is used for not.

like image 36
dmeister Avatar answered Sep 30 '22 19:09

dmeister