I’m attempting to use Google’s Guava ImmutableSet class to create a set of immutable classes with timelike properties (java.util.Date, and org.joda.time.DateTime).
private static final ImmutableSet<Class<?>> timeLikeObjects = ImmutableSet.of(Date.class, DateTime.class);
I’m completely stumped as to why I’m getting this compiler error (Java 1.6 in eclipse).
Type mismatch: cannot convert from ImmutableSet<Class<? extends Object&Serializable&Comparable<? extends Comparable<?>>>> to ImmutableSet<Class<?>>
Note that this works:
private static final ImmutableSet<?> timeLikeObjects = ImmutableSet.of(Date.class, DateTime.class);
However I obviously loose part of the generic description of the timeLikeObjects type.
I’ve never run across the ampersand symbol in a generic description, and it doesn’t appear to be valid syntax.
Is there a way to specify multiple inheritance in Java Generics that I’m just missing?
Basically the compiler is trying to be smart for you. It’s working out some bounds for you, and trying to use them for the return type of
of.Fortunately, you can fix it by being explicit:
The
&part is valid syntax – it’s how you specify bounds for multiple types, e.g.That means you can only specify types for
Twhich implementSerializableandComparable<T>.