java泛型通配符使用,何时在Java泛型中使用通配符?

this is from HeadFirst Java: ( page 575 )

This:

public void takeThing(ArrayList list)

Does the same thing as this:

public void takeThing(ArrayList extends Animal> list)

So here is my question: if they are exactly same, why don't we write

public extends Animal> void takeThing(ArrayList> list)

or

public void takeThing(ArrayList list)

Also, when would it be useful to use a ? instead of a T in a method declaration ( as above ) with Generics, or for a Class declaration? What are the benefits?

解决方案

The big difference between

public void takeThing(ArrayList list)

and

public void takeThing(ArrayList extends Animal> list)

is that in the former method you can refer to "T" within the method as the concrete class that was given. In the second method you cannot do this.

Here a more complex example to illustrate this:

// here i can return the concrete type that was passed in

public Map getNamesMap(ArrayList list) {

Map names = new HashMap();

for (T animal : list) {

names.put(animal, animal.getName()); // i assume there is a getName method

}

return names;

}

// here i have to use general Animal

public Map getNamesMap(ArrayList extends Animal> list) {

Map names = new HashMap();

for (Animal animal : list) {

names.put(animal, animal.getName()); // i assume there is a getName method

}

return names;

}

With the first method if you pass in an List of Cats you get a Map with Cat as key. The second method would always return a Map with general Animal key.

By the way this is not valid java syntax:

public extends Animal> void takeThing(ArrayList> list)

Using this form of generic method declaration you have to use a valid java identifier and not "?".

Edit:

The form "? extends Type" only applies to variable or parameter type declaration. Within a generic method declration it has to be "Identifier extends Type" as you are able to refer to the "Identifier" from within your method.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值