java - Populating ArrayList -


i trying populate array list, however, array list equals 0, , never initializes, despite declaring on main().

this code.

static arraylist<integer> array = new arraylist<integer>(10); //the parenthesis value changes size of array. static random randomize = new random(); //this means not pass 100 elements.  public static void main (string [] args) {     int tally = 0;     int randint = 0;      randint = randomize.nextint(100); //now set random value.     system.out.println(randint); //made when randomizing number didn't work.     system.out.println(array.size() + " : array size");      (int = 0; < array.size(); i++)     {         randint = randomize.nextint(100); //now set random value.         array.add(randint);         tally = tally + array.get(i); //add element total in array.     }            //system.out.println(tally); } 

can tell me going on? feel rather silly, i've done arraylists default arrays , cannot figure out save life!

new arraylist<integer>(10) creates arraylist initial capacity of 10 size still 0 there no elements in it.

arraylist backed array underneath create array of given size (initial capacity) when constructing object doesn't need resize every time insert new entry (arrays in java not dynamic when want insert new record , array full need create new 1 , move items, that's expensive operation) though array created ahead of time size() return 0 until add() list.

that's why loop:

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

will not execute array.size() 0.

change to:

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

and should work.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -