初始化列表< T>给定数量的空值而没有循环? [英] Initializing List<T> with given number of nulls without loop?
问题描述
是否可以将List<T>
初始化为包含给定数量的null
,其中T是列表是其成员的类的类型参数?我当然可以通过循环来做到这一点,但想知道是否可以不这样做.
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);
创建一个给定容量但大小为0的列表,因此对于所有x
,myList.get(x)
均失败,例如. myList.set(numEls-1,null)
.
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]);
不编译,并且
myList = (List<T>) Arrays.asList(new Object[numEls]);
在Eclipse中进行编译(带有未选中的强制转换警告),但不能在javac中进行编译.
compiles in Eclipse (with an Unchecked cast warning), but not with javac.
更新:谢谢您的回答!但是,我找到了另一个很短的解决方案,接近于我上一次尝试的解决方案,该解决方案可以在eclipse中使用我们的自动构建系统进行编译:对数组进行广播,而不对列表进行广播!
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]);
推荐答案
如果您想要ArrayList
,则可以使用反射来作弊
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);
这篇关于初始化列表< T>给定数量的空值而没有循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!