user2720349
user2720349

Reputation: 35

Java: Iterating through an Array List

I have an ArrayList containing names of instantiated objects that I want to execute the method 'count' on. I'm unsure if/how to do that, though. I have a loop to scan through the array list, and added pseudocode with what I'm trying to achieve.

    n = 0;
    while(n <= arrayList.size()){
        (arrayList.get(n)).count();
    }

I'm new to java and am not sure this is possible, but any help would be appreciated. Thanks.

Upvotes: 2

Views: 24301

Answers (2)

luoluo
luoluo

Reputation: 5533

You have several ways to do so:

Basic1:

n = 0;
while (n < arrayList.size()) {
    (arrayList.get(n)).count();
    n++;
}

Basic2:

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

Better1:

for(ClassTypeOfArrayList item: arrayList) {
    item.count();
} 

Better2:

Iterator iterator = arrayList.iterator();
while(iterator.hasNext()){
    System.out.println(iterator.next());
}

Upvotes: 1

raffian
raffian

Reputation: 32106

Simpler way to do it...

ArrayList<MyObject> list = ...
for( MyObject obj : list)
  obj.count()

Upvotes: 2

Related Questions