0

I need to implement a Map which must have a custom hash (returns an integer- year + car model number) and it also has to be sorted in decreasing order. If I use a TreeMap, I cannot make a custom hash, and if I use a HashMap, I cannot order it. How can I use both? I tried making a TreeMap with a custom comparator for decreasing order but it ignores my overriding of the hashCode and adds elements that should be in different places on the same place, even though their hashcodes are different. How can I solve this?

class MyComparator implements Comparator<Integer> {
    public int compare(Integer a, Integer b) {
        if (a < b) {
            return 1;
        }
        return 0;
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Jay_Peters
  • 101
  • 1
  • 3
  • 11
  • Post your code. Your comparator is wrong if it returns 0 for keys that should be different. We can't explain more without your code. – JB Nizet Nov 07 '17 at 21:53
  • TreeMap does not use hashCode(). Feel free to implement any hash code you want. –  Nov 07 '17 at 21:58
  • It would be better if you edited your question to include all your relevant code, rather than posting some of it in a comment. – dave Nov 07 '17 at 21:59
  • What about if `a > b`? – tsolakp Nov 07 '17 at 22:03
  • 2
    It may not solve all your problems, but your comparator is incomplete, ie. it never returns a negative value. Read the specification for [compare()](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-) and make sure you follow it. – dave Nov 07 '17 at 22:04
  • it returns 0. I am a little confused, as I am a beginner in Java and implemented it as I would have for sorting in C – Jay_Peters Nov 07 '17 at 22:05
  • From memory, C and Java have the same specification for comparators. You should return `<0`, `0` or `>0` depending on the two values. – dave Nov 07 '17 at 22:08
  • treating all cases (a>b, a – Jay_Peters Nov 07 '17 at 22:08
  • @Jay_Peters Integers have a natural order. If you want them in decreasing order, Just use https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#reverseOrder--. You said you want to define a hashCode based on year and car model. And now you're showing a comparator of integers. So where are your year and car model? – JB Nizet Nov 08 '17 at 07:18

1 Answers1

1

TreeMaps order elements using their compareTo methods (if the elements are comparable) or a given comparator. They do not use hashCode() at all, so you can have any implementation you want.

Your problem is probably with the comparator itself. You probably have cases in which two equal elements have the same hashCode, but the comparator doesn't return 0 for them. So you expect the TreeSet to have only one of these elements, but it doesn't see them as equal to each other.

Malt
  • 28,965
  • 9
  • 65
  • 105