java - Passing an instance of Comparable to a method that expects a Comparator -
the stream class in java 8 defines max method requires comparator argument. here method signature:
optional<t> max(comparator<? super t> comparator) comparator functional interface has abstract compare method signature. notice compare requires 2 arguments.
int compare(t o1, t o2) the comparable interface has abstract compareto method signature. notice compareto requires 1 argument.
int compareto(t o) in java 8, following code works perfectly. however, expected compilation error like, "the integer class not define compareto(integer, integer)".
int max = stream.of(0, 4, 1, 5).max(integer::compareto).get(); can explain why it's possible pass instance of comparable method expects instance of comparator though method signatures not compatible?
that's nice feature method references. note integer::compareto instance method. need 2 integer objects call it. 1 on left side (the target object), , 1 on right side (the first , parameter).
so integer::compareto method reference method, expects 2 integer objects , returns int. comparator<integer> functional interface functions, expect 2 integer objects , return int. that's reason why works.
Comments
Post a Comment