[英]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] [编辑]
map.keySet().toArray()[0]
map.keySet().toArray()[0]
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.