0

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?

noMAD
  • 7,744
  • 19
  • 56
  • 94

2 Answers2

3

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

Your implementation of the compare method violates the contract. It is supposed to return 0 if two objects are equal. That's why it doesn't work.

kraskevich
  • 18,368
  • 4
  • 33
  • 45