public interface Map { … }
Now, we replace K
with String
as the key type. We’ll also replace V
with Integer
as the value type:
Map map = new HashMap<>();
map.put("Duke", 30);
map.put("Juggy", 25);
// map.put(1, 100); // This line would cause a compile-time error
This example shows a HashMap
that maps String
keys to Integer
values. Adding a key of type Integer
is not allowed and would cause a compile-time error.
Examples of using generic types in Java
Now let’s look at some examples that will demonstrate further how to declare and use generic types in Java.
Using generics with objects of any type
We can declare a generic type in any class we create. It doesn’t need to be a collection type. In the following code example, we declare the generic type E
to manipulate any element within the Box
class. Notice in the code below that we declare the generic type after the class name. Only then we can use the generic type E
as an attribute, constructor, method parameter, and method return type: