I’m curious why we need the diamond operator in Java7? We can simulate this behaviour with a simple static generic method, which could be added to the collections API:
Code of the method for HashMap:
public static <R, S> HashMap<R, S> getInstance() {
return new HashMap<R, S>();
}
And we can use it this way:
Map<String, List<String>> m = HashMap.getInstance();
And code when you can try this behaviour:
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Arrays;
public class Diamond {
public static void main(String... args) {
Map<String, List<String>> m = getInstance();
m.put("Hello", Arrays.asList("Peter", "Robert"));
System.out.println(m.toString());
}
public static <R, S> HashMap<R, S> getInstance() {
return new HashMap<R, S>();
}
}
While you are correct that one can use a generic factory method to avoid repeating type parameters when creating generic objects, that approach has a couple of disadvantages: