What is <K, V> in a hash map and how to use it in my class?

I'm trying to just get a name for what is called the <> part of an ad that is unlucky. Can someone tell me what he called, how can I use it in my class? For example, I can try to make my own collection and use new MyThing<String> , for example. Any help is appreciated, thanks!

+6
source share
2 answers

This is a generic class type declaration. For example, to indicate that the card will use strings as keys and integers as values:

 Map<String, Integer> mymap = new HashMap<String, Integer>(); 
+6
source

He called generics, and here is how you can use it:

 public class MyClass<MyType> { private MyType myItem; public MyClass(MyType item) { myItem = item; } public MyType getMyItem() { return myItem; } } 

Usually the type name ( MyType in this case) is T for "type" and K and V for "key" and "value", but I just make it easier to understand.

Then you can:

 MyClass<String> m = new MyClass<String>("potato"); System.out.println(m.getMyItem()); // prints "potato" 
+3
source

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


All Articles