0

I made several instances of objects in a hashtable and want to call a method from each of them.

I made a for that goes through an enumeration of the values retrieved from said hashtable, but I'm unsure how to actually call the method on each object.

for(Enumeration<Agent> AgentEnum = AgentList.elements(); AgentEnum.hasMoreElements();){
        //content+=
        AgentEnum.nextElement();
    }

Content should receive the return of the method I'm trying to call from class Agent.

Arfons
  • 96
  • 9

2 Answers2

0
content = AgentEnum.nextElement().<your-method>();
Oleg Gryb
  • 5,122
  • 1
  • 28
  • 40
  • I don't know what the should return. From the example in the code it looks like the author wanted to accumulate the values that the method returns. I've changed += to =, but again if the author is trying to sum something for all objects, he'll need to put += back. – Oleg Gryb Jun 22 '14 at 18:28
0

Iterate over the keys in your hashmap. For example:

Enumeration<Agent> AgentEnum = AgentList.keys();
while(AgentEnum.hasMoreElements()) {
    Agent key = AgentEnum.nextElement();
    YOUR_CLASS value = AgentList.get(key);
    value.whatever();
    ...
}

EDIT

Or use the values directly:

for(YOUR_CLASS obj : AgentList.values()) {
    obj.whatever();
    ...
}

Other methods are discussed here, for example.

Community
  • 1
  • 1
Christian St.
  • 1,751
  • 2
  • 22
  • 41
  • And that's a bad advice. If the goal is to call a method on each *value* of a Map, the OP should iterate on the *values* of the map, not on its keys. – JB Nizet Jun 22 '14 at 18:32
  • He's saying that enumeration goes through values, not keys. – Oleg Gryb Jun 22 '14 at 18:32