如何将单个地图条目添加到优先级队列 [英] How to add a single map entry to priority queue

查看:44
本文介绍了如何将单个地图条目添加到优先级队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我必须添加整个地图,如最后一行所示.

At the moment I have to add the whole map, as shown in the last line.

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());

如果我只想添加怎么办

("word" 5)

如果我这样做

sortedCells.add("word",5)

我收到一个参数错误.

如何添加单个元素?

推荐答案

你应该添加一个 Map.Entry 对象而不仅仅是 ("word", 5) 因为您的优先级队列的通用类型是 Map.Entry.在这种情况下,您可能应该创建自己的 Map.Entry 类:

You should add a Map.Entry object and not just ("word", 5) because the generic type of your priority queue is Map.Entry<String, Integer>. In this case you should probably create your own 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;
    }
}

在您的代码中,您现在可以调用:

In your code you can now call:

sortedCells.add(new MyEntry("word",5));

如果您不想实现自己的条目,可以使用 AbstractMap.SimpleEntry:

If you don't want to implement your own entry you could use AbstractMap.SimpleEntry:

sortedCells.add(new AbstractMap.SimpleEntry<String, Integer>("word",5));

这篇关于如何将单个地图条目添加到优先级队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆