开发者

Java: Using a hashmap, retrieving all values and calling methods

I have a need to store a list of dynamically created objects in a way where they can all be retrieved and their methods called on demand.

As far as I can see for the list and creation, a HashMap fits my needs but i'm a bit puzzled on recalling the objects and calling their methods using the HashMap.

Just as a reference, let me give you a little code:

He开发者_运维知识库re is the HashMap:

Map<String, Object> unitMap = new HashMap<String, Object>();

// here is how I put an object in the Map notice i'm passing coordinates to the constructor:
unitMap.put("1", new Worker(240, 240));
unitMap.put("2", new Worker(240, 240));

Now I need to create a method that retrieves every object in the hashmap and call a method from each object. is this possible or can the created objects only be referenced directly. If so, is there another way to call a method of all existing instances of a class dynamically (in other words, on user input)?


Sure. You can do this:

for (Object thing : unitMap.values()) {
    // use "thing" here
}

If you need the keys too, you can either get just the keys:

for (String key : unitMap.keySet()) {
    // use "key" here
}

or both the keys and values together:

for (Map.Entry<String, Object> entry : unitMap.entrySet()) {
    // use "entry.getKey()" and "entry.getValue()"
}

In all the above cases, each entry in the map is traversed one by one. So at the end of the loop, you'll have processed all the entries in the map.


If all of the values in the Map are Worker objects, you should declare your map to be of type Map<String, Worker>. This way, when you pull a value out of the map, it will be typed as a Worker. This way you can call any method declared on Worker as opposed to having to check the type at runtime using instanceof.

If the map holds different values, and you need to keep the value type as Object, it may be advantageous to use an interface to define the method that you want to call for each different object type.

If you do not know what method you want to run on the values until runtime, and the map can hold different values, you will just have to do what you are currently doing, and use Map<String, Object>.

Finally, to get the values of the map, you do just as Chris Jester-Young mentioned before me. The biggest advantage, as I said previously, is that your objects will be typed, and you will have no need for casting/instanceof checking.


I use this to put all values from hashMap on a List, hope it helps.

private List<String> getValuesFromHashMap(HashMap<String, String> hashMap) {

    List<String> values = new ArrayList<String>();

    for (String item : hashMap.values()) {
        values.add(item);
    }

    return values;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜