Populating ArrayList

狂风中的少年 提交于 2020-01-03 18:03:50

问题


I am trying to populate an array list, however, my array list constantly equals 0, and never initializes, despite my declaring it over main().

This is my code.

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);
}

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!


回答1:


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 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++) {
 // ...
}

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

Change it to:

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

And it should work.



来源:https://stackoverflow.com/questions/29381607/populating-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!