Java Generics: Unknown wildcards and T

2

I could verify that in Java we can use both a wildcard ("?") and the "T" (what is this?) to create generic mechanisms (classes, methods, interfaces ...). But it has not been clear to me what are the main differences between these devices and when to use one or the other. Could someone help, please?

    
asked by anonymous 12.04.2016 / 20:15

2 answers

2

First, T may well be replaced by E or Z or TYPE . It is just the name given to the generic type parameter.

Most of the time, the following letters chosen by convention:

Note that for T it should be seen as class rather than typo , by definition all of them represent a type anyway.

About wildcards , it can not be used in a statement. This can only be used in generic context (between <> ) when it does not know the type.

Examples:

public <?> ? foo(? bar) //não irá compilar.

public <T> T foo(T bar) //ele irá compilar.

public foo(List<?> bar) //ele irá compilar.
    
13.04.2016 / 03:10
2

By convention, T is used to represent a type parameter , or type parameter , used in the declaration of a generic class.

As already mentioned in Jean's response, there is a convention for more common cases, although you can use any letter in practice.

A classic example is the declaration of class List , which represents a list of elements. So we have:

public interface List<E> extends Collection<E> { ... }

At the time of using the list, we can then define the type E of the list, like this:

List<String> nomes = new ArrayList<>();

And now the compiler will warn if we try to put anything other than String in the list.

Only sometimes we want to explicitly leave a list without a defined type. This could only be done with List , but in this case the compiler will think you forgot to declare the type.

For this we use the wildcard ? , as in the example:

int contar(List<?> qualquerTipo) {
    return qualquerTipo.size();
}

Note that I do not need to know the type to count the elements of the list, so it is a perfectly valid use.

There are other applications for this, but it is generally a type of generic meta-programming used in utilitarian frameworks or routines where the actual type does not matter.

This should not be used frequently in system implementations we do on a day-to-day basis, as it is much more insecure.

    
13.04.2016 / 04:20