Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code explanation in Java

Tags:

java

generics

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

like image 653
Gandalf StormCrow Avatar asked Apr 27 '10 08:04

Gandalf StormCrow


People also ask

What is a code in Java?

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.

What is Java with explanation?

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.


2 Answers

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 Strings, 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".

like image 154
Lars Andren Avatar answered Sep 30 '22 09:09

Lars Andren


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.

like image 44
Ham Vocke Avatar answered Sep 30 '22 07:09

Ham Vocke