Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface in generic type Java

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

like image 891
user2740884 Avatar asked Aug 04 '14 21:08

user2740884


People also ask

Can an interface have a generic type Java?

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.

How is a generic interface defined?

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.


2 Answers

& 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

like image 197
Lucas Ross Avatar answered Oct 26 '22 21:10

Lucas Ross


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

like image 30
Bohemian Avatar answered Oct 26 '22 21:10

Bohemian