Interface in general Java

Today I found strange code in jdk8 sources and did not find any explanation.

static final Comparator<ChronoLocalDate> DATE_ORDER = (Comparator<ChronoLocalDate> & Serializable) (date1, date2) -> { return Long.compare(date1.toEpochDay(), date2.toEpochDay()); }; 

Can someone explain to me why and Serializable from <> ?
And it would be great to provide a link to the documentation.

Source Link: AbstractChronology

+8
java generics java-8 interface
source share
2 answers

& in this context indicates type intersection. Say you have classes like this:

 interface SomeInterface { public boolean isOkay(); } enum EnumOne implements SomeInterface { ... } enum EnumTwo implements SomeInterface { ... } 

You want to be able to use any enumeration that implements SomeInterface as a type parameter in a generic type. Of course, you want to use methods for both Enum and SomeInterface, for example, compareTo and isOkay , respectively. Here's how to do it:

 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

+3
source share

There are two parts to your question:

What is & Serializable ?

This is a type intersection - the type must be either Comparator<ChronoLocalDate> or Serializable

why is it not in angle brackets < > ?

Because its cast, not the general type of parameter

+1
source share

All Articles