Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What mean <K,V> before HashMap<K,V>? Generics in Java [duplicate]

Tags:

java

generics

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>?

like image 975
Ruslan Kryzhanovskiy Avatar asked Jan 18 '26 17:01

Ruslan Kryzhanovskiy


1 Answers

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();
...
like image 198
Eran Avatar answered Jan 21 '26 05:01

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!