发布于2023-04-25 阅读(0)
扫一扫,手机访问
先简单来段例子:
public void testGenerics() {
Collection numbers = new ArrayList<>();
numbers.add(1); // ok
Collection> tmp = numbers;
// don't work, you don't know what type 'tmp' obviously contains
// tmp.add(1);
Collection extends Number> tmp2 = numbers;
// don't work, you don't know what subtype 'tmp2' obviously contains
// tmp2.add(1);
Collection integers = new ArrayList<>();
tmp = integers;
tmp2 = integers;
Collection strings = new ArrayList<>();
tmp = strings;
// tmp2 = strings; // don't work
}
这个问题其实有点反人类,估计大部分人(包括我)对这种转换的第一反应肯定是“当然是对的。。”,说下我的理解:
Collection
Collection extends Number>:表示这个Collection是Number类型的“某个子类型”的Collection实例,可以是Collection
Collection
说到为什么在不明确类型的情况下不能允许写操作,那是为了运行期的安全,举个例子:
public void testGenerics2() {
List integers = new ArrayList<>();
List extends Comparable> comparables = integers;
integers.add("1");
comparables.get(0).intValue(); // fail
}
如果comparables允许添加Comparable类型,那么运行期就有可能会抛出一些意料之外的RuntimeException,导致方法不正常结束甚至程序crash。
现在再来说说Collection
public void testGenerics3() {
List integers = new ArrayList<>();
List objects = integers; // don't work
List> objects1 = integers; // ok
}
Collection>表示的范围比Collection
表示任意类型集合的正确写法是Collection>;
Collection
为什么Collection
public void testGenerics4() {
List integers = new ArrayList<>();
List objects = new ArrayList<>();
// this will be ok if List equals List>
// objects = strings;
// objects.add("1");
// Integer i = (Integer) objects.get(0); // and crashes
List> objects1 = new ArrayList<>(); // ok
// objects1.add("1"); // compiler will make it illegal
}
List
List>编译器是不允许往里面丢数据的,因为不知道List到底是哪种数据类型的集合,不能用obj instanceof UnknownType判断;
?才是表示未知类型,Object表示的是已知类型;
如果List
上一篇:java自定义注解的方法
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8