How to add a single map entry to priority queue

点点圈 提交于 2019-12-06 10:56:50

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

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

sortedCells.add(new AbstractMap.SimpleEntry<String, Integer>("word",5));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!