简体   繁体   English

如何通过索引获取TreeMap的键?

[英]How to get the key of a TreeMap by it's index?

So I'm trying to get the key of a TreeMap by an int index.所以我试图通过 int 索引获取 TreeMap 的键。

Here's my code:这是我的代码:

TreeMap<String, Integer> map = new TreeMap<String, Integer>(Collections.reverseOrder());
map.put("hi", 1);
map.put("hi2", 5);

System.out.println("Key: " + (String) map.keySet().toArray()[0] + "\nValue: " + map.get(0));

But when I execute this, I get the error:但是当我执行这个时,我收到错误:

java.lang.Integer cannot be cast to java.lang.String

So I'm trying to get the key: "hi2"所以我试图得到钥匙:“hi2”

The problem is问题是

"\nValue: " + map.get(0)

The argument for get must be a String , not an Integer like 0 . get的参数必须是String ,而不是0类的Integer So do this:所以这样做:

String key = map.keySet().toArray()[0];
Integer value = map.get(key);
System.out.println("Key: " + key + "\nValue: " + value);

It seems to me that the error comes from the latter part of the println statement:在我看来,错误来自println语句的后半部分:

println(...map.get(0))

Where the integer 0 has a type conflict with the map, where the key type is String .其中整数0与映射存在类型冲突,其中键类型为String

[edit] [编辑]

  • As for the original question about getting the key by index, I think you did it correctly: map.keySet().toArray()[0]至于关于通过索引获取密钥的原始问题,我认为你做对了: map.keySet().toArray()[0]
  • For the error complaining about key type conflict in map.get() , you can correct the parameter type, as suggested by @Tichodroma's answer above.对于在map.get()抱怨键类型冲突的错误,您可以更正参数类型,如上面@Tichodroma 的回答所建议的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM