我试图填充一个数组列表,但是,我的数组列表始终等于 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
with 初始容量为 10 但大小仍然为 0,因为其中没有元素。
ArrayList
由下面的数组支持,因此它在构造对象时会创建一个给定大小(初始容量)的数组,因此不需要每次插入新条目时都调整其大小(Java 中的数组是not动态的,因此当您想要插入新记录并且数组已满时,您需要创建一个新记录并移动所有项目,这是一项昂贵的操作)但即使数组是提前创建的size()
将返回0
直到你真正add()
清单上的东西。
这就是这个循环的原因:
for (int i = 0; i < array.size(); i++) {
// ...
}
不会执行为array.size()
is 0
.
将其更改为:
for (int i = 0; i < 10; i++)
它应该有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)