填充ArrayList

3

我正在尝试填充一个数组列表,但是我的数组列表始终等于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);
}

有人可以告诉我发生了什么吗?我感到很愚蠢,我一直使用ArrayList作为我的默认数组,但是我无论如何都解决不了这个问题!


我的数组列表一直等于0,你是指元素都是零吗?还是指元素数量为零? - Tarik
1个回答

2
new ArrayList<Integer>(10)创建一个初始容量为10的ArrayList,但大小仍为0,因为其中没有元素。

ArrayList在底层由数组支持,所以在构建对象时会创建一个给定大小(初始容量)的数组,因此它不需要每次插入新条目时都调整大小(Java中的数组是动态的,因此当您要插入新记录且数组已满时,您需要创建一个新数组并移动所有项目,这是昂贵的操作),但即使提前创建了数组,size()也会返回0,直到您将某些内容add()到列表中。

这就是为什么这个循环:

for (int i = 0; i < array.size(); i++) {
 // ...
}

由于array.size()0,所以不会执行。

更改为:

for (int i = 0; i < 10; i++)

它应该能够正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接