Java 如何将单个映射条目添加到优先级队列
现在我必须添加整个地图,如最后一行所示Java 如何将单个映射条目添加到优先级队列,java,priority-queue,Java,Priority Queue,现在我必须添加整个地图,如最后一行所示 PriorityQueue<Map.Entry<String, Integer>> sortedCells = new PriorityQueue<Map.Entry<String, Integer>>(3, new mem()); Map<String,Integer> pn = new HashMap<String,Integer>(); pn.put("hello
PriorityQueue<Map.Entry<String, Integer>> sortedCells = new PriorityQueue<Map.Entry<String, Integer>>(3, new mem());
Map<String,Integer> pn = new HashMap<String,Integer>();
pn.put("hello", 1);
pn.put("bye", 3);
pn.put("goodbye", 8);
sortedCells.addAll(pn.entrySet());
如果我这样做
sortedCells.add("word",5)
我得到一个参数错误
如何添加单个元素?您应该添加一个
Map.Entry
对象,而不仅仅是(“word”,5)
,因为优先级队列的通用类型是Map.Entry
。在这种情况下,您可能应该创建自己的Map.Entry
class:
final class MyEntry implements Map.Entry<String, Integer> {
private final String key;
private Integer value;
public MyEntry(String key, Integer value) {
this.key = key;
this.value = value;
}
@Override
public String getKey() {
return key;
}
@Override
public Integer getValue() {
return value;
}
@Override
public Integer setValue(Integer value) {
Integer old = this.value;
this.value = value;
return old;
}
}
如果您不想实现自己的条目,可以使用:
sortedCells.add(新的AbstractMap.SimpleEntry(“word”,5));
尽管这不会造成严重问题,但如果我打印sortedcells,它会显示:[你好=1,再见=3,测试。MyEntry@a32b,再见=8],我怎样才能得到考试。MyEntry@a32b显示为word=5?另外,最好将my entry类放在一个单独的java文件中,还是放在同一个文件中?我编辑了这个问题,您可以使用SimpleEntry
,而不是您自己的(我在编写原始问题后发现的)SimpleEntry
实现了toString()
,您将得到相同的结果。或者只需在MyEntry中实现toString()
。如果这是一个重复出现的用例,并且您希望拥有自己的结构,我将使用MyEntry
(使用不同的描述性名称)。如果它像您介绍的那样简单,我会使用SimpleEntry
yes,如果在myEntry中实现了toString函数,它确实会产生所需的输出
final class MyEntry implements Map.Entry<String, Integer> {
private final String key;
private Integer value;
public MyEntry(String key, Integer value) {
this.key = key;
this.value = value;
}
@Override
public String getKey() {
return key;
}
@Override
public Integer getValue() {
return value;
}
@Override
public Integer setValue(Integer value) {
Integer old = this.value;
this.value = value;
return old;
}
}
sortedCells.add(new MyEntry("word",5));
sortedCells.add(new AbstractMap.SimpleEntry<String, Integer>("word",5));