填充 ArrayList [英] Populating ArrayList

查看:17
本文介绍了填充 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试填充一个数组列表,但是,尽管我通过 main() 声明了它,但我的数组列表始终等于 0,并且从不初始化.

I am trying to populate an array list, however, my array list constantly equals 0, and never initializes, despite my declaring it over 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,但我无法解决这个问题来挽救我的生命!

Can someone tell me what is going on? I feel rather silly, I've done ArrayLists for my default arrays and I cannot figure this out to save my life!

推荐答案

new ArrayList(10) 创建一个 ArrayList 具有初始容量 为 10 但大小仍为 0,因为其中没有元素.

new ArrayList<Integer>(10) creates an ArrayList with initial capacity of 10 but the size is still 0 as there are no elements in it.

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

ArrayList is backed by an array underneath so it does create an array of a given size (initial capacity) when constructing the object so it doesn't need to resize it every time you insert a new entry (arrays in Java are not dynamic so when you want to insert a new record and the array is full you need to create a new one and move all the items, that's an expensive operation) but even though the array is created ahead of time size() will return 0 until you actually add() something to the list.

这就是为什么这个循环:

That's why this loop:

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

不会执行,因为 array.size()0.

Will not execute as array.size() is 0.

改为:

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

它应该可以工作.

这篇关于填充 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆