I have came across the piece of code:
public static <K,V> HashMap<K,V> newHashMap() {
return new HashMap<K,V>();
}
and we can use this to create an instance of HashMap
, like this:
Map<String, List<String>> anagrams = newHashMap();
Now the question is the method newHashMap
is called without passing the required type ( in this case its (String, List<String>
), but still java is creating the correct type. How?
I'm confused here, how K,V
is getting bounded to the type that is mentioned left side of the code:
Map<String, List<String>>
without even passing on :
newHashMap();
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
A Generic class can have muliple type parameters.
This is called type inference. It's the
Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.
See also:
That's because it is of the correct type.
It is a common mistake to see the generics of an object as part of the type of the object. It is not. In fact the generics are completely removed once compilation is complete. This is called type erasure.
A Map<String,String>
is actually just a Map
. The <String,String>
part is only used by the compiler to ensure that you use it correctly in your code.
Java does not store the generics information. So when the compiler is done with your code, the map will be the equivalent of HashMap<Object, Object>()
. Generics only allow the compiler to verify you don't pass the wrong types to functions and automatically (and safely) cast objects your retrieve from it.
So regardless of the type you create, it always stores Object
s.
Because your method (newHashMap()
) doesn't do anything with the map (like trying to add an element. This function works with any generic parameters you chose. The calling side does know the used generic types, so it can verify you don't try to store the wrong type of objects in it.
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