Java Generics Type Conversion Puzzle

I am trying to use the Google Guava ImmutableSet class to create a set of immutable classes with temporary properties (java.util.Date and org.joda.time.DateTime).

private static final ImmutableSet<Class<?>> timeLikeObjects = ImmutableSet.of(Date.class, DateTime.class); 

I am completely at a dead end why I get this compiler error (Java 1.6 in eclipse).

 Type mismatch: cannot convert from ImmutableSet<Class<? extends Object&Serializable&Comparable<? extends Comparable<?>>>> to ImmutableSet<Class<?>> 

Please note that this works:

 private static final ImmutableSet<?> timeLikeObjects = ImmutableSet.of(Date.class, DateTime.class); 

However, I have clearly lost some of the general description of type timeLikeObjects.

I have never come across the ampersand symbol in the general description, and it does not seem to be valid syntax.

Is there a way to specify multiple inheritance in Java Generics that I just miss?

+6
source share
1 answer

Basically, the compiler is trying to be smart for you. It develops some constraints for you and tries to use them for the return type of .

Fortunately, you can fix this by being explicit:

 private static final ImmutableSet<Class<?>> timeLikeObjects = ImmutableSet.<Class<?>>of(Date.class, DateTime.class); 

The & part is the actual syntax - this is how you specify the boundaries for several types, for example.

 public class Foo<T extends Serializable & Comparable<T>> 

This means that you can only specify T types that implement Serializable and Comparable<T> .

+17
source

Source: https://habr.com/ru/post/915517/


All Articles