Java:使用哈希图,检索所有值并调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6366278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:36:05  来源:igfitidea点击:

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

javaandroidobjectmethodshashmap

提问by cody

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.

就我所看到的列表和创建而言,HashMap 符合我的需要,但我对使用 HashMap 调用对象和调用它们的方法感到有些困惑。

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

只是作为参考,我给你一点代码:

Here 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)?

现在我需要创建一个方法来检索哈希图中的每个对象并从每个对象调用一个方法。这是可能的还是只能直接引用创建的对象。如果是这样,是否有另一种方法可以动态调用类的所有现有实例的方法(换句话说,根据用户输入)?

回答by Chris Jester-Young

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.

在上述所有情况下,地图中的每个条目都被一个一个地遍历。所以在循环结束时,您将处理地图中的所有条目。

回答by nicholas.hauschild

If all of the values in the Map are Workerobjects, 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 Workeras opposed to having to check the type at runtime using instanceof.

如果 Map 中的所有值都是Worker对象,则应将映射声明为类型Map<String, Worker>。这样,当您从地图中拉出一个值时,它将被输入为Worker. 通过这种方式,您可以调用任何声明的方法Worker,而不必在运行时使用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.

如果映射持有不同的值,并且您需要将值类型保持为Object,那么使用接口来定义您要为每个不同的对象类型调用的方法可能会更有利。

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

如果在运行时之前不知道要对值运行什么方法,并且映射可以保存不同的值,那么您只需要做当前正在执行的操作,并使用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.

最后,要获取地图的值,您可以按照我之前提到的 Chris Jester-Young 进行操作。正如我之前所说,最大的优点是您的对象将被键入,并且您将不需要强制转换/实例化检查。

回答by César Cobo

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

我用它来将 hashMap 中的所有值放在一个列表中,希望它有所帮助。

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

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

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

    return values;
}