Java Generic Class

In this blog post we will cover what are java generics and what they are good for. Also, we will explain what is a java generic class and how to define it.

Java Generics

Generics were introduced to java in JDK 5. Its’ purpose is to enforce data type correctness by evaluating it during the compile-time. By using generics we make our applications less error-prone. In addition, generics allow us to define code that could be used with several different types. Therefore, it helps to reduce duplicate code in our applications. A good example for generic code usage is for example sorting algorithms.

We can have different generic types in java. These include generic classes and generic interfaces. Generics in java can also be used to define generic methods.

Java Generic Type Naming Convention

By convention the generic type names are single uppercase letters. This is quite different from the variable naming convention. You might wonder why is that so. The reason behind it is actually very simple. By having different naming conventions it just makes it easier for developers to understand/read the code. We can easily distinguish for example between regular class or interface and generic type names.

Following are the most commonly used type parameter names:

  • E – Element (used extensively by the Java Collections Framework)
  • K – Key
  • N – Number
  • T – Type
  • V – Value
  • S,U,V etc. – 2nd, 3rd, 4th types

Java Generic Class (and Interface)

Java generic class is a class that is parameterized over one or more types. This and all following is also true for interfaces. Generic classes/interfaces help to reduce duplicate code. For example, we can see the use of generics in the List interface.

public interface List<E> extends Collection<E> {
    // ...
}

Here we can see a generic type E that stands for elements by the generics naming convention. We can say that the List interface is parameterized over type E. This means that List can hold objects of any type. It doesn’t matter if it holds Integers or Strings. It will still work the same way for each of these types. Even better, we don’t need to deal with different classes for each data type we want to hold in a list. Luckily, there are no list classes that would be called something like StringList or IntegerList. Instead, all we need to do is to define a generic type argument, the data type the list will hold, when we instantiate a List. In the following example the generic type argument is Integer. This helps us to get rid of boilerplate code.

List<Integer> integers = new ArrayList<>();

One real-life example of a generic class could be an ice cream cone. An ice cream cone can hold as many different types of ice cream as you can imagine: chocolate, vanilla, cherry. You name it! We don’t need to have separate cones for chocolate ice cream or vanilla ice cream. One type of cone is enough to hold that tasty ice cream in it.

Defining a Java Generic Class

A java generic class looks similar to a “regular” class. The difference is that we can define a generic type argument to be used within the class. This type argument we have to define after the class name and put it inside the diamond operator(<>). But let’s see how to define a generic class of our own to make it easier to understand.

In the following example we will define a generic class named GenericClass that defines a generic type T. By doing this, we can store any object type in the variable t defined in the class. Also, we can set its’ value through the setter and retrieve it by using the defined getter.

Notice how we create an instance of the GenericClass and define it a type argument Integer. Later, we also instantiate a GenericClass with a type argument of String instead. This is a simple usage of generics and how we can create generic code. By doing so, we avoid creating duplicate code by not needing to define separate classes for Integer and String types.

public class GenericClass<T> {

    private T t;

    public void setT(final T t) {
        this.t = t;
    }

    public T getT() {
        return this.t;
    }

    public static void main(String[] args) {
        // Create an instance of a generic class
        // Define the generic argument Integer
        GenericClass<Integer> integerType = new GenericClass<>();
        integerType.setT(1);

        // Display
        System.out.println(integerType.getT());

        // Create an instance of a generic class
        // Define the generic argument String
        GenericClass<String> stringType = new GenericClass<>();
        stringType.setT("string");

        System.out.println(stringType.getT());
    }
}

Output:

1
string

Conclusion

Generics were introduced in JDK 5. Its’ purpose is to enforce data type correctness by evaluating it during the compile-time. In addition, generics allow us to define generic code that could be used by multiple data types. This allows us to reduce the amount of duplicated code.

Be the first to reply

Leave a Reply

Your email address will not be published. Required fields are marked *