AFAIK since java 8 bucket structure was changed from linked list to tree.
So in case hashCode() method return constant and our key class implements Comparable interface then complexity to get element from single cell will be reduced from O(n) to O(log n).
I tried to check it:
public static void main(String[] args) {
int max = 30000;
int times = 100;
HashMap<MyClass, Integer> map = new HashMap<>();
HashMap<MyComparableClass, Integer> compMap = new HashMap<>();
for(int i = 0; i < max; i++) {
map.put(new MyClass(i), i);
compMap.put(new MyComparableClass(i), i);
}
long startTime = System.nanoTime();
for (int i = max; i > max - times; i--){
compMap.get(new MyComparableClass(i));
}
System.out.println(String.format("Key is comparable: %d", System.nanoTime() - startTime));
startTime = System.nanoTime();
for (int i = max; i > max - times; i--){
map.get(new MyClass(i));
}
System.out.println(String.format("Key isn't comparable: %d", System.nanoTime() - startTime));
}
MyComparableClass:
public class MyComparableClass
implements Comparable {
public Integer value;
public MyComparableClass(Integer value) {
this.value = value;
}
@Override
public int compareTo(Object o) {
return this.value - ((MyComparableClass) o).value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyComparableClass myClass = (MyComparableClass) o;
return value != null ? value.equals(myClass.value) : myClass.value == null;
}
@Override
public int hashCode() {
return 1;
}
}
MyClass is the same as MyComparableClass but doesn't implement Comparable interface.
And unexpectedly i always get results where time for getting value by non comparable key less than by comparable.
Key is comparable: 23380708
Key isn't comparable: 10721718
Can someone explain?