将数组输入到Hashmap中(Inputting Arrays into a Hashmap)

我觉得这是一个非常简单的问题,但我找不到答案。

你能把数组对象输入到HashMap的put方法吗?

例:

假设你有一个HashMap: HashMap<Integer, String> map = new HashMap <Integer, String>();

你有一个整数数组和一个方便的字符串数组。 数组未按如下所示进行初始化,但包含未知值(这更容易说明结果)。

int[] keys = {1, 3, 5, 7, 9}; String[] values = {"turtles", "are", "better", "than", "llamas"};

我希望HashMap的键值对是:

1, turtles 3, are 5, better 7, than 9, llamas

这可以通过map.put(keys, values)来实现吗? 我知道这不起作用,你应该得到一个错误,如“ HashMap类型中的方法put(Integer,String)不适用于参数(int [],String []) ”。 我只想要比以下更有效,更优雅或更紧凑的东西:

for (int i=0; i < keys.length; i++) { map.put(keys[i],values[i]); }

I feel like this is a very simple question, but I couldn't find an answer.

Can you input an array object to the put method of a HashMap?

Example:

Say you have a HashMap: HashMap<Integer, String> map = new HashMap <Integer, String>();

You have an array of integers and an array of strings conveniently given. The arrays are not initialized as shown below, but contain unknown values (this is just easier for illustrating the result).

int[] keys = {1, 3, 5, 7, 9}; String[] values = {"turtles", "are", "better", "than", "llamas"};

I want the key-value pairs of the HashMap to be:

1, turtles 3, are 5, better 7, than 9, llamas

Can this be achieved with something like map.put(keys, values)? I know this doesn't work, you should get an error like "The method put(Integer, String) in the type HashMap is not applicable for the arguments (int[], String[])". I just want something more efficient, elegant, or compact than:

for (int i=0; i < keys.length; i++) { map.put(keys[i],values[i]); }

最满意答案

我无法想象

for (int i=0; i < keys.length; i++) { map.put(keys[i],values[i]); }

可以提高效率。 如果这是你经常要做的事情那么我可能会在Map周围写一个帮助对象。

请注意,如果要添加的值在地图中,则Map.putAll()存在。

I can't imagine that

for (int i=0; i < keys.length; i++) { map.put(keys[i],values[i]); }

could be made much more efficient. If it's the sort of thing you're going to do often then I'd perhaps write a helper object around Map.

Note that Map.putAll() exists if the values you want to add are already in a map.

更多推荐