Having trouble Implementing a Custom Comparator for a TreeSet (Dijkstra's)

一曲冷凌霜 提交于 2019-12-06 13:40:29

You received the error because the AbstractMap.SimpleEntry class doesn't implement Comparable. A TreeSet that isn't given a Comparator must assume that its elements are Comparable, but they aren't.

You were right to determine that you need to create a Comparator, to tell the TreeSet how to order the elements.

Create your own class that implements Comparator<AbstractMap.SimpleEntry<Integer, Integer>>. In the compare method, extract the weights and compare them.

public class WeightComparator implements
    Comparator<AbstractMap.SimpleEntry<Integer, Integer>>
{
    @Override
    public int compare(AbstractMap.SimpleEntry<Integer, Integer> one,
                       AbstractMap.SimpleEntry<Integer, Integer> two)
    {
        return Integer.compare(one.getValue(), two.getValue());
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!