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?
Generics means parameterized types. The idea is to allow type (Integer, String, … etc, and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is called ...
Type conversion in Java with Examples. When you assign value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and if not then they need to be casted or converted explicitly.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
Generics in Java is similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. There are some fundamental differences between the two approaches to generic types. Generic Class Like C++, we use <> to specify parameter types in generic class creation.
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:
private static final ImmutableSet<Class<?>> timeLikeObjects =
ImmutableSet.<Class<?>>of(Date.class, DateTime.class);
The &
part is valid syntax - it's how you specify bounds for multiple types, e.g.
public class Foo<T extends Serializable & Comparable<T>>
That means you can only specify types for T
which implement Serializable
and Comparable<T>
.
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