开发者

Java - What's <> used and what's its name?

I'm working through some sample code and then this appeared:

public abstract class RandomPool<T> extends Pool {
     //Class...
}

What's <> used for? And why is just T inside these? This seems to be very random for me. However, how can I use i开发者_StackOverflowt in a longer perspective of making programs?

Thanks and tell me if I need to add more details!


See Java Generics

T stands for "Type"


Generics

T is a placeholder for whatever type is used at runtime. For example you could use:

RandomPool<String> pool;

T would refer to String in that case.

Read the Java Generics Tutorial


That thing is called a type parameter.

Basically, your class RandomPool is a generic class. It has a type parameter so that it could use different classes provided by caller. See Java collections like List it will be much more clear.

Also, note that T is not a keyword, you could name the type parameter any way you like. It's just a convention to use T like Type. Some collections use E like Element.


This is how you declare the type of a Generic that your class accepts. The example you presented reads:

abstract class ObjectPool of type T extends Pool


very short desc T is a compiler variable. with your code posted you can have a randomPool of Strings, eg: RandomPool<String> a randomPool of Foos, eg: RandomPoo<Foo>, .... Pretty much anything.

read dom farr's link with this in mind


It's the java way (Generics) to implement templates (in C++). T represents the type of the element you want to use for a particular object instantiated.

You can easily understand generics by looking at this example:

Hashmap <String, int> hm = new HashMap<String,int>();
hm.put("k1",1);
hm.put("k2",2);

Iterator it = hm.iterator();

while (it.hasNext()){
    String curr = it.next();
    int value = hm.get(curr);
}

Here, you can understand that Hashmap takes 2 types (general types, you can use whatever you want.. from Natives to custom classes etc etc). RandomPool, in the example you posted, should be instantiated with a particular custom type! So, when you decide to use it, you should write code this way (i.e.):

RandomPool<String> myR = new RandomPool<String>();


There's nothing fancy about this. It's just Java's syntax for rank-1 parametric polymorphism.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜