Saturday, November 16, 2024

Find out how to use generics in your Java packages


public interface Map<Ok, V> { … }

Now, we change Ok with String as the important thing kind. We’ll additionally change 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 reveals a HashMap that maps String keys to Integer values. Including a key of kind Integer just isn’t allowed and would trigger a compile-time error.

Examples of utilizing generic sorts in Java

Now let’s have a look at some examples that can exhibit additional the way to declare and use generic sorts in Java.

Utilizing generics with objects of any kind

We will declare a generic kind in any class we create. It doesn’t must be a set kind. Within the following code instance, we declare the generic kind E to govern any factor throughout the Field class. Discover within the code beneath that we declare the generic kind after the category identify. Solely then we will use the generic kind E as an attribute, constructor, methodology parameter, and methodology return kind:

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles