Java - what is the <?> and GENERIC TYPES for?

Asked

Viewed 226 times

0

I’m not sure, but I suppose the question is part of Reflection do Java, but I wanted to know what it is for, and where I can study generic types, preface in Portuguese, because my English is not very good ;-; (I’m learning to improve in studies)

  • 1

    Would this answer your question? https://answall.com/questions/15799/tipo-gen%C3%A9rico-em-java

1 answer

4


That one <?> is known as wildcard type (Wild Card). It is part of the generic types. With it you can receive a generic of any type. For example:

    List<?> curinga = null;
    List<String> string = Arrays.asList("Andrei", "skqo");
    List<Integer> inteiros = Arrays.asList(1, 2);

    curinga = string; // SEM PROBLEMAS
    curinga = inteiros; // SEM PROBLEMAS

Answering the question:

Generic types serve to make implementation more flexible. They accept a larger number of different types.

Defined wildcards:

Now look at another example:

    List<? extends Number> numeros = null;
    List<String> strings = Arrays.asList("Maria", "Jose");

    numeros = strings; // ERRO EM TEMPO DE COMPILAÇÃO

The above implementation is not accepted by the compiler as the list numeros receives any type that extends from Number. Therefore, it is not possible to assign a list of strings to it.

But this is possible:

    List<? extends Number> numeros = null;
    List<Double> doubles = Arrays.asList(20.0, 12.1);
    List<Integer> inteiros = Arrays.asList(2,1);

    numeros = doubles; // sem problemas
    numeros = inteiros; // sem problemas

Completion

Generics are great for reusing classes and methods because they can be parameterized by type. But there is loss of information of the types during its execution. For example a List<String> is actually just one List when using generics. And this can cause problems like performance.

There are many sites on the Internet that take good care of the subject (in my humble opinion). One way to understand how they work is by reading about it and doing simple tests equal the examples I put up.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.