2

I am looking at the source code of the Comparator.comparing method implemented in Java8

here is the code

public static <T, U> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor,
        Comparator<? super U> keyComparator)
{
    Objects.requireNonNull(keyExtractor);
    Objects.requireNonNull(keyComparator);
    return (Comparator<T> & Serializable)
        (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),
                                          keyExtractor.apply(c2));
}

Why the bit-wise and between Comparator and Serializable is required and what it does?

(Comparator<T> & Serializable)

It can be simply casted to Comparator for chaining.

also how does bit-wise operations works in case of non numeric values?

Thanks.

Saravana
  • 12,647
  • 2
  • 39
  • 57
  • 1
    Related: http://stackoverflow.com/questions/22819804/what-is-the-type-of-an-intersected-type – assylias Nov 12 '16 at 15:56
  • also related: https://stackoverflow.com/questions/30374083/whats-the-meaning-of-the-character-in-the-returned-value – danny Sep 01 '19 at 05:07

2 Answers2

3

That's not a bitwise operation between types but an intersection type, indicating to the compiler that, when it generates the type corresponding to the lambda expression, this type should implement both Comparator and Serializable interfaces.

Nándor Előd Fekete
  • 6,988
  • 1
  • 22
  • 47
2

The single & is not a bitwise operator in this case. It is an intersection of types Comparator AND Serializable. You are asserting that you want the return type to implement both Comparator and Serializable. The trick here is that you can take the intersection of interfaces as long as the intersection results in only a single abstract method. See https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.16

The bitwise operators (&, ^, |) may be used to compare booleans and numeric types, but that is not what is happening here. See https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.22

mttdbrd
  • 1,791
  • 12
  • 17