I'm reading the book Effective programming in Java and during the reading I met such a code snippet:
public static <К, V> HashMap<K, V> newInstance() {
return new HashMap<K, V>();
}
what does the expression <K, V> between static and HashMap<K,V> how it is called and works? I've heard about generics, but I do not know them well and I want to know why it's impossible to write some like:
public static HashMap<K, V> newInstance() {
return new HashMap<K, V>();
}
why before HashMap<K, V> I need to write <К, V>?
When you write
public static HashMap<K, V> newInstance() {
return new HashMap<K, V>();
}
K and V are regular identifiers that must be resolved to some type (class name or interface name).
For example, if you wanted a method that returns a HashMap having a String key and Integer value, you could write:
public static HashMap<String,Integer> newInstance() {
return new HashMap<String,Integer>();
}
This method will always return a HashMap<String,Integer>, so you can only assign it to:
HashMap<String,Integer> map = newInstance();
However, if you want K and V to be generic type parameters, you must declare them as such. That's what you do with <K,V>:
public static <К, V> HashMap<K, V> newInstance() {
return new HashMap<K, V>();
}
This allows you to use this method to return HashMaps of different key and value types:
HashMap<String,Integer> map1 = newInstance();
HashMap<Long,Boolean> map2 = newInstance();
...
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