Code explanation in Java
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
pr开发者_如何学运维ivate 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 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.
Imagine you're writing a List or Array class. This class must be able to hold elements of an unknown type. How do you do that?
Generics answers this question. Those <T>
you're seeing can be read as some type
. With generics you can write class MyList<T> { ... }
, which in this context means a list that holds some type
.
As an usage example, declare a list to store integers, MyList<Integer> listOfInts
, or strings, MyList<String> listOfStrings
, or one class you've written yourself MyList<MyClass> listOfMyClass
.
What you are seeing is Java generics, which allows classes and methods to be parameterized by other classes. This is especially useful when creating container classes, since it saves you having to create separate classes for "a list of integers", "a list of strings", etc. Instead, you can have a single "list of some type T, where T is a variable" and then you can instantiate the list for some specific type T. Note that Java generics is not quite the same as template types in C++; Java generics actually use the same class definition but add implicit casting (generated by the compiler) and add additional type-checking. However, the different instantiations actually make use of the same exact type (this is known as erasure), where the parameterized types are replaced with Object. You can read more about this at the link.
Since noone has mentioned it yet, there is a very comprehensive guide/FAQ/tutorial on generics which can be found on Angelika Langer's site.
精彩评论