简体   繁体   中英

How to iterate elements of an integer arraylist in Java

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!

The easiest way would be to use a for each loop

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

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.
}
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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM