Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird Java generic

Tags:

java

generics

What does this mean?

HashBiMap<Character, Integer> charOcc = HashBiMap.<Character, Integer> create();
like image 944
nanda Avatar asked Jan 12 '10 15:01

nanda


2 Answers

create() is a generic method. Since it's static and has no parameters (hence no type inference), the only way you can tell it what the generic parameters are is by that strange-looking .<Character, Integer> syntax.

Edit: This is actually not necessary in this specific case; the compiler can infer the generic types from the left-hand side. But it is sometimes necessary in other cases, such as this question: Generic method in Java without generic argument

like image 165
Michael Myers Avatar answered Sep 28 '22 02:09

Michael Myers


It's calling a generic static method (create()) using Character and Integer as the type arguments. For instance, if you're looking at the Google Java Collections, the declaration has this signature:

public static <K,V> HashBiMap<K,V> create()

The <K,V> part on its own specifies that those are type parameters for the method.

The equivalent call in C# would be one of:

HashBiMap.Create<Character, Integer>();
HashBiMap<Character, Integer>.Create();

depending on whether you wanted it to be a generic method in a nongeneric type, or a nongeneric method in a generic type.

The positioning of type parameters and type arguments in Java is unintuitive IMO.

like image 26
Jon Skeet Avatar answered Sep 28 '22 03:09

Jon Skeet