java的泛型引用_使用通配符的Java自引用泛型

是否可以指定未知泛型类型是自引用的?

尝试失败:

import java.util.*;

class Generics {

public enum A { A1, A2 }

public enum B { B1, B2 }

public static List extends Enum>> listFactory(String[] args) {

if (args.length == 0) {

return new ArrayList(Arrays.asList(A.A1, A.A2));

} else {

return new ArrayList(Arrays.asList(B.B1, B.B2));

}

}

public static void main(String[] args) {

List extends Enum>> lst = listFactory(args);

dblList(lst);

System.out.println(lst);

}

public static > void dblList(List lst) {

int size = lst.size();

for (int i = 0; i < size; i++) {

lst.add(lst.get(i));

}

}

}

这会导致编译错误:

Generics.java:17: error: method dblList in class Generics cannot be applied to given types;

dblList(lst);

^

required: List

found: List

reason: inferred type does not conform to declared bound(s)

inferred: CAP#1

bound(s): Enum

where EType is a type-variable:

EType extends Enum declared in method dblList(List)

where CAP#1 is a fresh type-variable:

CAP#1 extends Enum> from capture of ? extends Enum>

1 error

理想情况下,listFactory()的返回类型将表示该列表包含自引用泛型类型(其确切类型未知).

这可能吗?如果是这样,listFactory()和lst的类型应该是什么?

最佳答案 有效的Java Item 28不鼓励在返回类型中使用通配符:

Do not use wildcard types as return types. Rather than providing additional flexibility for your users, it would force them to use wildcard types in client code.

Properly used, wildcard types are nearly invisible to users of a class. They cause methods to accept the parameters they should accept and reject those they should reject. If the user of a class has to think about wildcard types, there is probably something wrong with the class’s API.

这是EJ描述的问题的一个很好的例子. listFactory()实际上只是返回一个List< Enum>但是通过声明一个通配符返回类型,你必须通过箍来完成看似简单的任务.

如果你给listFactory()一个像这样的签名:

public static List> listFactory(String[] args)

您也可以清理dblList()的签名:

public static void dblList(List lst)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值