填充ArrayList [英] Populating ArrayList

查看:123
本文介绍了填充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<Integer>(10)创建初始容量为10的ArrayList,但是大小仍然为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.

这就是该循环的原因:

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

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

将其更改为:

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

它应该可以工作.

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

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