Today I found strange code into jdk8 sources and couldn't find any explanation.
static final Comparator<ChronoLocalDate> DATE_ORDER =
(Comparator<ChronoLocalDate> & Serializable) (date1, date2) -> {
return Long.compare(date1.toEpochDay(), date2.toEpochDay());
};
Can anyone explain me why & Serializable
out of <>
?
And it would be great to provide link on documentation.
Link to source: AbstractChronology
Java Generic Interface In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.
A generic interface is primarily a normal interface like any other. It can be used to declare a variable but assigned the appropriate class. It can be returned from a method. It can be passed as argument.
&
in that context indicates an intersection of types. Say you have classes like these:
interface SomeInterface
{
public boolean isOkay();
}
enum EnumOne implements SomeInterface { ... }
enum EnumTwo implements SomeInterface { ... }
You want to be able to use any enum that implements SomeInterface as a type parameter in a generic type. Of course, you want to be able to use methods on both Enum and SomeInterface, such as compareTo
and isOkay
, respectively. Here's how that could be done:
class SomeContainer<E extends Enum<E> & SomeInterface>
{
SomeContainer(E e1, E e2)
{
boolean okay = e1.isOkay() && e2.isOkay();
if (e1.compareTo(e2) != 0) { ... }
}
}
See http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.9
There are two parts to your question:
what is
& Serializable
?
It's a intersection of types - the type must be both Comparator<ChronoLocalDate>
and Serializable
why is it not in angle brackets
< >
?
Because its a cast, not a generic parameter type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With