Can a List<T>
be initialized to contain a given number of null
s, 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]);
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.
Solution. Yes, We can insert null values to a list easily using its add() method.
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));
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With