• Fri. Nov 15th, 2024

How to use generics in your Java programs

Byadmin

Sep 26, 2024



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.

Naming conventions for generics
We can declare our generic type in any class we want. We can use any name to accomplish that, but preferably, we should use a naming convention. In Java, type parameter names are usually single uppercase letters:

E for Element
K for Key
V for Value
T for Type

Since we can name the type of parameter we want, avoid using meaningless names like “X,” “Y,” or “Z.”

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:



Source link