Java Generics Methods : The Secret to Cleaner, Faster Code

Izzat Arramsyah
3 min readSep 21, 2024

INTRODUCTION

Generics means parameterized types. Generics allow us to create classes, interfaces, and methods with different data types. To understand the importance of generics, let’s take a look at the code example in the following generics class.

Circle

But what if we want to assign a value to a variable?

String circle = object.get(0);

If we look at that code, it will result in an error. The error occurs because the compiler does not know the data type of the object. To resolve this error, we need to add casting.

String circle = (String) object.get(0);

But what if our code continues to grow and this happens in many lines of code? This would certainly make things difficult. The solution to the problem above is to use Generics. What we need to do is define the data type of the List object.

--

--