public interface Map { … }
Now, we exchange Okay
with String
as the important thing sort. We’ll additionally exchange V
with Integer
as the worth sort:
Map 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 sort Integer
just isn’t allowed and would trigger a compile-time error.
Examples of utilizing generic sorts in Java
Now let’s take a look at some examples that can display additional the best way to declare and use generic sorts in Java.
Utilizing generics with objects of any sort
We are able to declare a generic sort in any class we create. It doesn’t should be a set sort. Within the following code instance, we declare the generic sort E
to govern any ingredient throughout the Field
class. Discover within the code beneath that we declare the generic sort after the category identify. Solely then we are able to use the generic sort E
as an attribute, constructor, methodology parameter, and methodology return sort: