2

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!

3 Answers 3

4

The easiest way would be to use a for each loop

for(int elem : yourArrayList){
   elem;//do whatever with the element
}
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.