问题
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]);
回答1:
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);
回答2:
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.
回答3:
What you probably want is something like this....
final int maxSize = 50;
List<T> v = new Vector<T>() {{setSize(maxSize);}};
Vectors allow you to set a size, which fills them with null's.
回答4:
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));
回答5:
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.
回答6:
I would just use a loop, its simpler and likely to be faster as well.
List<T> list =
while(list.size()<size) list.add(null);
Any other approach you use is likely to use a loop for you. If this is fine, just write your own method which hides the loop used.
回答7:
new option with streams:
List resultColumn = IntStream.range(0, 10000).mapToObj(i -> null).collect(Collectors.toList());
回答8:
Try this:
List<String> list = new ArrayList<String>(Arrays.asList(new String[100]));
for(String string : list){
System.out.println(string);
}
Well, you can write a hierarchy:
class Base<T>{
protected List<T> list;
public List<T> getList(){
return list;
}
}
class Child extends Base<String>{
public Child(){
list = new ArrayList<String>(Arrays.asList(new String[100]));
}
}
It can be used in the next way:
Base<String> base = new Child();
base.getList();
回答9:
What I did was
MyClass[] array = {new MyClass(), new MyClass(), new MyClass(), new MyClass(), new ProfileSectionDTO(), new MyClass()};
List<MyClass> MyClassList = Arrays.asList(array);
Dirty, but working :)
来源:https://stackoverflow.com/questions/8223177/initializing-listt-with-given-number-of-nulls-without-loop