this morning I came across this code, and I have absolutely no idea what that means. Can anyone explain me what do these <T> represent? For example:
public class MyClass<T>
...
some bits of code then
private Something<T> so;
private OtherThing<T> to;
private Class<T> c;
Thank you
You have bumped into “generics”. They are explained very nicely in this guide.
In short, they allow you to specify what type that a storage-class, such as a
ListorSetcontains. If you writeSet<String>, you have stated that this set must only containStrings, and will get a compilation error if you try to put something else in there:Furthermore, another useful example of what generics can do is that they allow you to more closely specify an abstract class:
In this way, the extending classes does not have to extend
Variable, but they need to extend a class that extendsVariable.Accordingly, a method that handles an
AbstClasscan be defined like this:where
?is a wildcard that means “all classes that extendAbstClasswith someVariable“.