我正在尝试填充一个数组列表,但是,我的数组列表始终等于 0,并且从不初始化,尽管我在 main() 中声明了它。
这是我的代码。
static ArrayList<Integer> array = new ArrayList<Integer>(10); //The parenthesis value changes the size of the array.
static Random randomize = new Random(); //This means do not pass 100 elements.
public static void main (String [] args)
{
int tally = 0;
int randInt = 0;
randInt = randomize.nextInt(100); //Now set the random value.
System.out.println(randInt); //Made when randomizing number didn't work.
System.out.println(array.size() + " : Array size");
for (int i = 0; i < array.size(); i++)
{
randInt = randomize.nextInt(100); //Now set the random value.
array.add(randInt);
tally = tally + array.get(i); //add element to the total in the array.
}
//System.out.println(tally);
}
谁能告诉我这是怎么回事?我觉得很傻,我已经为我的默认数组完成了 ArrayLists,但我无法解决这个问题来挽救我的生命!
最佳答案
new ArrayList<Integer>(10)
创建一个 ArrayList
初始容量为 10,但大小仍然为 0,因为其中没有元素。
ArrayList
由下面的数组支持,因此它在构造对象时确实创建了一个给定大小(初始容量)的数组,因此它不需要在每次插入新条目时都调整它的大小(Java 中的数组不是 动态所以当你想插入一个新记录并且数组已满时你需要创建一个新记录并移动所有项目,这是一个昂贵的操作)但即使数组是提前创建的size()
将返回 0
直到你真的add()
列表中的内容。
这就是为什么这个循环:
for (int i = 0; i < array.size(); i++) {
// ...
}
不会作为 array.size()
执行是0
.
将其更改为:
for (int i = 0; i < 10; i++)
它应该可以工作。
关于java - 填充数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29381607/