20.9 C
New York
Thursday, September 26, 2024

The best way to use generics in your Java applications




public interface Map<Okay, V> { … }

Now, we exchange Okay with String as the important thing kind. We’ll additionally exchange V with Integer as the worth kind:


Map<String, Integer> map = new HashMap<>();
map.put("Duke", 30);
map.put("Juggy", 25);
// map.put(1, 100); // This line would trigger a compile-time error

This instance exhibits a HashMap that maps String keys to Integer values. Including a key of kind Integer isn’t allowed and would trigger a compile-time error.

Examples of utilizing generic varieties in Java

Now let’s take a look at some examples that may reveal additional learn how to declare and use generic varieties in Java.

Utilizing generics with objects of any kind

We are able to declare a generic kind in any class we create. It doesn’t should be a group kind. Within the following code instance, we declare the generic kind E to control any factor throughout the Field class. Discover within the code under that we declare the generic kind after the category identify. Solely then we are able to use the generic kind E as an attribute, constructor, technique parameter, and technique return kind:



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles