Java Generics for Beginners

Nimesha Wijepala
3 min readNov 12, 2020

Introduction

As a java programmer, we all have to face coding errors called bugs during both compile-time and runtime. We all have more or fewer mistakes in our codes but it is always easier to identify compile-time issues than runtime ones. On the other hand, it is always worth letting the compiler know about memory allocation and validation of variables for better type safety. Well, Java 5 introduced their solution, Generics alias parameterized types.

Using Generics with Collections

We use java collections to handle data structures and implement logic related to them. But using Generics we can implement our data structures in a type-safe manner, simply let the compiler check what kind of data should be added to our data structure. Let’s follow the examples.

List studentName = new ArrayList();studentName.add("Tom");studentName.add("Jerry")

Here we create a list to add student names. Usually, we keep student names as Strings. But java compiler does not know it should contain Strings during compile time. Then we have to cast its values to Strings when retrieving. See below.

String firstStudent = (String)list.get(0);

But if you use Generics, casting is not needed. See the code snippet below.

List <String> studentName = new ArrayList<String>(); 
// since java 7 you can write as List <String> studentName = new ArrayList<>();
studentName.add("Tom");studentName.add("Jerry");String firstStudent = list.get(0);

Well, isn’t it easy to let the compiler handle the thing?

Do you have any idea why casting is required when you don’t use Generics? The reason is that ArrayList is a generic class that implements List generic interface and extends AbstractList generic class. Let’s see how to implement generic classes and methods and why.

Generic Classes and Interfaces

Generic class or interface is simply called a parameterized class or interface over type. See the below example for Generic class implementation.

public class Item < T > {
private T itemType;
public void setItemType(T itemType) {
this.itemType = itemType;
}
public T getItemType() {
return itemType;
}
public static void main(String[] args) {
Item < String > word = new Item < > ();
Item < Integer > number = new Item < > ();
word.setItemType(new String("Word"));
number.setItemType(new Integer(1));
System.out.println(word.getItemType());
System.out.println(number.getItemType());
}
}

It does not need to access Object class for reusable classes anymore. T, type variable can be any non-primitive variable, and the compiler identifies it during compilation. Using the same mechanism we can implement generic interfaces too.

Naming Conventions

As per Java documentation type parameters should be single and upper case. The following are some of them which are commonly used.

T - type

E - element (have used in data structures in java collections such as List, ArrayList and etc)

K - key

V - value

Generic Methods

If someone needs to implement a static or non-static method with its own parameter type, the Generic Method would take place for sure. There can be one or more parameter types written in a Generic Method. We can simply call it a normal method invocation. Let’s go with examples.

public class GenericTester {
public static < E > void displayElement(E element) {
System.out.println("Element is " + element);
}
public static void main(String[] args) {
Integer number = 1;
String word = "hello";
displayElement(number);
displayElement(word);
}
}

It is similar to the normal method implementation. The only difference is <E>, the parameterized return type.

<E> can be any non-primitive variable such a String, Integer and etc.

Conclusion

In a nutshell, Generics is for increasing the type-safety and reusability of our code. On the other hand, it reduces object casting errors during runtime because the compiler does the validation job. So, let’s use Generics for more quality codes.

--

--

Nimesha Wijepala

One who work in software industry as well as loves writing. Trying to combine both for sharing knowledge all over the world.