I wrote a utility in Java:
public static final ImmutableSortedSet<TimeUnit> REVERSED_TIMEUNITS = ImmutableSortedSet.copyOf( Collections.<TimeUnit>reverseOrder(), EnumSet.allOf(TimeUnit.class) ); public static Map<TimeUnit,Long> getCascadingDateDiff(long millies,TimeUnit maxTimeUnit) { if ( maxTimeUnit == null ) { maxTimeUnit = TimeUnit.DAYS; } Map<TimeUnit,Long> map = new TreeMap<TimeUnit,Long>(Collections.<TimeUnit>reverseOrder()); long restInMillies = millies; Iterable<TimeUnit> forUnits = REVERSED_TIMEUNITS.subSet(maxTimeUnit,TimeUnit.MICROSECONDS);
It works with:
Map<TimeUnit,Long> map = new TreeMap<TimeUnit,Long>(Collections.reverseOrder());
But I tried it first
Map<TimeUnit,Long> map = Maps.newTreeMap(Collections.reverseOrder());
My IntelliJ says nothing, and my compiler says:
DateUtils.java: [302,48] incompatible types; no instance (s) of type variable K, V exists so that java.util.TreeMap matches java.util.Map [ERROR] found: java.util.TreeMap [ERROR] required: java.util.Map
It works fine without a comparator:
Map<TimeUnit,Long> map = Maps.newTreeMap();
But I tried:
Map<TimeUnit,Long> map = Maps.newTreeMap(Collections.<TimeUnit>reverseOrder());
And with the help of:
Map<TimeUnit,Long> map = Maps.newTreeMap(new Comparator<TimeUnit>() { @Override public int compare(TimeUnit timeUnit, TimeUnit timeUnit1) { return 0; } });
And I have the same error. So it seems that every time I use a comparator in TreeMap, type inference no longer works. Why?
Guava Method Signature:
public static <C, K extends C, V> TreeMap<K, V> newTreeMap(Comparator<C> comparator)
The expected type of the return type is of type, so without a comparator, Java can conclude that K = TimeUnit and V = Long.
Using a comparator like TimeUnit, Java knows that C is TimeUnit. He also knows that the expected return type is of type therefore K = TimeUnit and V = Long. K extends C is respected since TimeUnit extends TimeUnit (anyway, I also tried to use Object Comparator if you think this is wrong ...)
So just wondering why type inference doesn't work in this case?