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
Java code runs on any machine that has JVM on it, without needing any special software. This allows Java developers to create “write once, run anywhere” programs, which make collaboration and distribution of ideas and applications easier.
Java is a widely used object-oriented programming language and software platform that runs on billions of devices, including notebook computers, mobile devices, gaming consoles, medical devices and many others. The rules and syntax of Java are based on the C and C++ languages.
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 List
or Set
contains. If you write Set<String>
, you have stated that this set must only contain String
s, and will get a compilation error if you try to put something else in there:
Set<String> stringSet = new HashSet<String>();
stringSet.add("hello"); //ok.
stringSet.add(3);
^^^^^^^^^^^ //does not compile
Furthermore, another useful example of what generics can do is that they allow you to more closely specify an abstract class:
public abstract class AbstClass<T extends Variable> {
In this way, the extending classes does not have to extend Variable
, but they need to extend a class that extends Variable
.
Accordingly, a method that handles an AbstClass
can be defined like this:
public void doThing(AbstClass<?> abstExtension) {
where ?
is a wildcard that means "all classes that extend AbstClass
with some Variable
".
What you see here is something called Generics. They were introduced to Java in release 1.5.
You can read about them here and here. Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With