I have been making my way through the Java Tutorial and have been reading about generic type inference in JDK7.
I came across the following syntax…
class MyClass<X> {
<T> MyClass(T t) {
// ...
}
}
MyClass<Integer> myObject = new <String`> MyClass<>("");
…which is a little confusing. I understand the ‘diamond’ operator and how generic types can be inferred based on the context.
I’m not sure why you’d use the diamond operator to infer the type passed to the constructor whilst explicitly specifying the type “String`” as well? Nor do I understand why the backtick is involved!
Also, is there a difference between the following?
MyClass<Integer> myObject1 = new <String> MyClass<>(""); // JDK7 only
MyClass<Integer> myObject2 = new MyClass<>(""); // JDK7 only
MyClass<Integer> myObject3 = new <String> MyClass<Integer>("");
is just
that is, you are
1. creating an instance of MyClass<Integer>
2. invoking the constructor with String as a type parameter:
The diamond operator has nothing to do with the constructor, as it does not “infer the type passed to the constructor” yet it infers the type passed to the whole class.
Oh, and I think the backtick in the tutorial example is probably a typographic error. 🙂