When and why should I use classes templates Class<T> in Java?


When I see that a class receives it, I find it scary.


In C++ this can be called a template , but in Java these classes are called generic.

This is necessary when a class can use the same basic structure and algorithms with different types of data. Think of something that can be done just like Boolean , Integer , Long , Float , etc. Everything is the same, it only changes the type of data that will be used to store it in the class. How do you solve this? Make a class for each of these types, copying them and just changing the type?

When you have to do maintenance, will you remember to do them all the same? There are no conditions, right?

Then you can use the generics . With this, you can vary the basic data type that will be used in the class according to the way it is instantiated. So this T there is a kind of "super variable", which will be replaced by a specific type when the class is instantiated.

class Exemplo<T> {
    private T x;
    Exemplo(T x) => this.x = x;
    public T getValue() => x;

Then use:

Exemplo<String> teste1 = new Exemplo<String>("teste");
Exemplo<Boolean> teste2 = new Exemplo<Boolean>(true);

I put it on GitHub for future reference .

Everything works. In the first example, every place that had the T , will turn into String . And the second where there was T turns Boolean , it would look something like this:

class Exemplo<String> {
    private String x;
    Exemplo(String x) {
        this.x = x;
    public String getValue() {
        return x;

So a single class solves the problem for all types without having to copy code, which will cause maintenance problems.

Java is full of these classes. Data collections often benefit a lot from this. In the beginning Java didn't have this feature, so you had a "naked" ArrayList anyway. So he accepted anything. It works, but imagine you can mix numbers, with String s, with Cliente s (a class you defined), with anything else. When creating such an ArrayList<T> , you create a variable that holds ArrayList<Cliente> and this list can only store Cliente . It's safer. Basically this is a collection that can be used with any type already existing in Java or created by programmers.

That's simply it. There are ways to use it more advanced, make restrictions on what types can be used in T , have other slots to generalize other parts with a different type, anyway… it asks as you use it and new doubts arise.

Documentation (continue following tutorial pages).

Scroll to Top