Search code examples
javatreemap

TreeMap with custom comparator doesn't remove entries


So I have a TreeMap with a simple custom comparator which sorts the map based on its values.

    Map<Integer, Double> unsortedMap = new HashMap<Integer, Double>();
    unsortedMap.put(..,..)
    ...
    ...

    Map<Integer, Double> map = new TreeMap<Integer, Double>(new SortValues(unsortedMap));

    public class SortValues implements Comparator<Integer> {
        Map<Integer, Double> map;

        SortValues(Map<Integer, Double> map) {
            this.map = map;
        }

        @Override
        public int compare(Integer one, Integer two) {
            if(map.get(one) >= map.get(two)) {
                return 1;
            } else
                return -1;
            }
        }
    }

I print out the map and it looks fine. But when I do map.remove(key) it doesn't remove it cause I still see it there when I print it. What am I missing here?


Solution

  • Your compare method is flawed, because it can't return 0. If the two objects are equal, then it needs to return 0, not 1.

    Change your compare method to return 0 if the two Integers are equal.

    This will allow the TreeMap to find the Integer, which relies on compare returning 0 to determine equality.