When and why should I use Class T class classes in Java?

17

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

    
asked by anonymous 04.02.2016 / 18:31

2 answers

16

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

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

When you have to do maintenance will you remember to do all the same? You do not have the conditions, right?

Then you can use the generics . This can vary the type of basic data that will be used in the class according to the form 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() {
        return x;
    }
}

Then use:

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

Everything works. In the first example, all places that had T will become String . And in the second where I had T become 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 be copying code, which will cause maintenance problems.

Java is full of these classes. Data collections often benefit greatly from this. In the beginning Java did not have this feature, so you had ArrayList "peeled" anyway. Then he would accept anything. It even works, but imagine that you can mix numbers, with String s, Cliente s (a class you defined), with anything else. When you created that% of ArrayList<T> , you create a variable that stores ArrayList<Cliente> and this list can only save Cliente s. It's safer. Basically this is a collection that can be used with any type already existing in Java or created by the programmers.

That's simply it. It has more advanced ways of using, restricting which types can be used in T , have other slots to generalize other parts with a different type, anyway ... it will ask as it is using and new questions arise.

Documentation (continue to follow the tutorial pages)

    
04.02.2016 / 18:44
0

Generics are also very useful in methods in this example:

    public static <T> List<T> asList(T... objects) {
       return ...
    }

you will receive a list of type T based on your parameters;

    
10.02.2016 / 21:26