Generics type parameters become limited without passing a real type

I came across a piece of code:

public static <K,V> HashMap<K,V> newHashMap() { return new HashMap<K,V>(); } 

and we can use it to create a HashMap instance, for example:

 Map<String, List<String>> anagrams = newHashMap(); 

Now the question is that the newHashMap method newHashMap called without passing the required type (in this case ( String, List<String> ), but still java creates the correct type. How?

I got confused here how K,V becomes the restricted type that is mentioned on the left side of the code:

 Map<String, List<String>> 

without even going through:

 newHashMap(); 
+5
source share
3 answers

This is called an output type . it

The ability of the Java compiler to view each method call and the corresponding declaration to determine the type argument (or arguments) that makes the call applicable. The output algorithm determines the types of arguments and, if available, the type to which the result is assigned or is returned. Finally, the output algorithm tries to find the most specific type that works with all arguments.

See also:

+7
source

This is because it is of the correct type.

A common mistake is to view the generics of an object as part of an object type. Is not. In fact, generics are completely removed after compilation is complete. This is called the erase type .

A Map<String,String> is actually just a Map . The <String,String> used only by the compiler to ensure that you use it correctly in your code.

+6
source

Java does not store generic information. Therefore, when the compiler is executed with your code, the map will be equivalent to HashMap<Object, Object>() . Generators allow the compiler to check whether you pass the wrong types to functions and automatically (and safely) throw objects that you extract from it.

Therefore, regardless of the type you create, it always stores Object s.

Because your method ( newHashMap() ) does nothing with the map (for example, trying to add an element). This function works with any universal parameters that you have selected. The caller knows the generic types used, so she can make sure that you are not trying to store the wrong type of objects in it.

+2
source

Source: https://habr.com/ru/post/1210652/


All Articles