2

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.

3
  • 1
    You have to increment your index n. Commented Aug 28, 2013 at 1:50
  • 1
    Wait, the list contains objects that support the method count(), right? What did you mean by containing names of instantiated objects?
    – raffian
    Commented Aug 28, 2013 at 1:54
  • Names as strings. I.e. "kiwi" would be an object that could execute kiwi.count. I got a good answer from raffian though. Commented Aug 28, 2013 at 2:04

2 Answers 2

2

Simpler way to do it...

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

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());
}
2
  • you forget the OO way , for(Iterator it = arrayList.iterator();it.hasNext();){ Object o= it.next();} or with a while
    – nachokk
    Commented Aug 28, 2013 at 3:01
  • In fact I viewed this problem at the point of a green hand. If you are new to java, using the first two is a fast way to get thing done. When you are familiar with java you may do anything you what. Thx.
    – luoluo
    Commented Aug 28, 2013 at 3:35

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.