Java ArrayList 添加超出当前大小的项目 [英] Java ArrayList add item outside current size
问题描述
想知道是否有一种有效的方法可以将项添加到 Java 的 ArrayList 的位置大于其当前大小的位置:
Wondering whether there is an efficient way to add an item to Java's ArrayList at a bigger position than its current size:
场景:
ArrayList<Item> items = new ArrayList<Item>;
... let's say I add three elements
现在我想在位置 10 添加一个项目(将 3 到 10 的项目保留为空)
Now I would like to add an item at position 10 (leaving items from 3 to 10 to null)
items.add(10,newItem); // item.size() == 3
是否有一种有效的方法可以用空值调整/填充 ArrayList 的大小?
Is there an efficient way resizing/filling an ArrayList with nulls?
Java 的实现将 size 字段设为私有 :-(..
Java's implementation makes size field private :-(..
推荐答案
恕我直言,你能做的最好的事情就是 items.addAll(Collections.nCopies(6, null))
并希望 ArrayList实现一些行为以在内部对其进行固定
imho the best thing you can do is items.addAll(Collections.nCopies(6, null))
and hope, that ArrayList implements some behaviour to internally fasten this up
这篇关于Java ArrayList 添加超出当前大小的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!