Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果数组用作HashMap中键对应的值,如何获取数组的单个值?_Java_Arrays_Hashmap - Fatal编程技术网

Java 如果数组用作HashMap中键对应的值,如何获取数组的单个值?

Java 如果数组用作HashMap中键对应的值,如何获取数组的单个值?,java,arrays,hashmap,Java,Arrays,Hashmap,在下面的代码中,我使用字符串数组作为对应于单个键的HashMap值。HashMap的get()方法返回整个数组。如果我想要单一值呢 数组的一部分。(比如)我只想要对应于键“Animal”的“Lion” class HMTest{ public static void main(String[] args){ HashMap<String, String[]> subjects = new HashMap<String, String[]>(); s

在下面的代码中,我使用字符串数组作为对应于单个键的
HashMap
值。
HashMap
get()
方法返回整个数组。如果我想要单一值呢 数组的一部分。(比如)我只想要对应于键“Animal”的“Lion”

class HMTest{
  public static void main(String[] args){
     HashMap<String, String[]> subjects = new HashMap<String, String[]>();
     subjects.put("Fruit",new String[] {"mango","orange"});
     subjects.put("Animal",new String[] {"Lion","Tiger"});

     for(String s:subjects.get("Animal"))
       System.out.println(s);
     }
  }
但这给了我错误

任何人都可以帮我

应该是:

System.out.println(subjects.get("Animal")[0]);
“Animal”
键的值是数组,而不是字符串。因此,当您
获取(“动物”)
时,您希望该值是一个数组。然后您需要获取第一个元素。

应该是:

System.out.println(subjects.get("Animal")[0]);

“Animal”
键的值是数组,而不是字符串。因此,当您
获取(“动物”)
时,您希望该值是一个数组。然后,您需要获取第一个元素。

对于,您不需要
get()
获取单个值

String[] s = subjects.get("Animal");
System.out.println(s[0]);

对于
,您不需要
get()
获取单个值

String[] s = subjects.get("Animal");
System.out.println(s[0]);

如果您尝试使用以下代码:

  for(String[] s:subjects.get("Animal"))
     System.out.println(s[0]);
如果它起作用,那么
subjects.get(“Animal”)
应该是
字符串[][]
的一种类型。但在您的代码中,它是一种
String[]
类型。他们不匹配


使用
System.out.println(subjects.get(“动物”)[0])
打印数组中的第一个元素。

如果尝试使用以下代码:

  for(String[] s:subjects.get("Animal"))
     System.out.println(s[0]);
如果它起作用,那么
subjects.get(“Animal”)
应该是
字符串[][]
的一种类型。但在您的代码中,它是一种
String[]
类型。他们不匹配


使用
System.out.println(subjects.get(“动物”)[0])
打印数组中的第一个元素。

由于HashMap的值是字符串数组,只需给出所需值的索引即可。喂,你想看《狮子》。因为它在动物数组中的索引是0,所以可以说

System.out.println(subjects.get("Animal")[0]);
输出:

Lion

因为HashMap的值是一个字符串数组,所以只需给出所需值的索引即可。喂,你想看《狮子》。因为它在动物数组中的索引是0,所以可以说

System.out.println(subjects.get("Animal")[0]);
输出:

Lion

对于
完全不是必需的。这也是我在for循环中尝试过的,但它给我的错误是说类型不兼容。@Winn Well。。不要在循环中使用它。我只是写了我的建议。for的
完全不是必需的。这也是我在for循环中尝试过的,但它给我的错误是说类型不兼容。@Winn Well。。不要在循环中使用它。我只是写了我的建议。