How to iterate elements of an integer arraylist in Java

17,345

Solution 1

The easiest way would be to use a for each loop

for(int elem : yourArrayList){
   elem;//do whatever with the element
}

Solution 2

for (int i = 0; i < arrayList.size(); i++) {

}

Or

Iterator<Object> it = arrayList.iterator();
while(it.hasNext())
{
    Object obj = it.next();
    //Do something with obj
}

Solution 3

Iterating over an array list is really simple.

You can use either the good old for loop or can use the enhanced for loop

Good Old for loop

int len=arrayList.size();
for(int i = o ; i < len ; i++){
int a =arrayList.get(i);
}

Enhanced for loop

for(int a : arrayList){
//you can use the variable a as you wish.
}
Share:
17,345
Abushawish
Author by

Abushawish

Android programming.

Updated on June 14, 2022

Comments

  • Abushawish
    Abushawish almost 2 years

    I understand that when you iterate a regular array element it is like so:

    int[] counter = new int[10];
    
    for loop{
       counter[i] = 0;
    }
    
    when button clicked{
      counter[0]++; //For example
      counter[6]++;
    }
    

    However I'm not understanding how to iterate through elements of an arraylist. If someone could help me understand I'll be appreciative. Thanks!

  • Benjamin Gruenbaum
    Benjamin Gruenbaum about 11 years
    "However I'm not understanding how to iterate through elements of an arraylist." I think OP said he understands how to use normal arrays but wondered how to iterate an ArrayList