java13------统配符、擦除

承接上一节泛型的定义:

泛型的定义不能包含继承作用。引入?表示统配符

无边界统配符、上届统配符,下界通配符:
public static void process(List<? extends Foo>

统配符具有继承概念:

List<? extends Integer> intList = new ArrayList<>();
List<? extends Number>  numList = intList;  // OK. List<? extends Integer> is a subtype of List<? extends Number>

泛型的规则:

1、读的时候,采用上界通配符。

2、写的时候,采用下界通配符。

3、有读有写的时候,不能采用统配符。有一种特例,先读后写是可以的

4、共性的属性,采用无界通配符。

 

类型擦除:

        1、泛型是在类型使用是在编译阶段中使用的:通过将泛型与统配符采用 Object对象与或者边界对象替代,以及增加类型转变,在运行阶段没有泛型的出现。

        2、编译系统会生成,桥函数。保证函数的多态性。---------

 

非具体类型:

          由于擦除机制,在运行阶段,没有对象的准备的信息的类型称为非具体类型。例如List<String> List<Number>在擦除后的都是List<Object>,所以系统不能分辨两种类型的区别。非边界的泛型与通配符。

          类型污染:当函数的参数为无长度的类型参数变量时,系统会认为一些操作是无法做到类型检查的,所以会造成堆污染。

         消除堆污染:当你认为不存爱堆污染的时候,可以增加注释告诉编译器,这个操作没有问题。

@SafeVarargs
@SuppressWarnings({"unchecked", "varargs"})

 

泛型的一些限制:原因擦除机制

          1、不能采用基本类型,作为泛型的参数。---------原因擦除后,都采用了对象

           2、不能对基本类型使用 instances of。原因泛型在运行阶段不存在

           3、由于静态变量是属于类的,所以泛型无法共享

           4、泛型,不能实例化

}

When creating a Pair object, you cannot substitute a primitive type for the type parameter K or V:

Pair<int, char> p = new Pair<>(8, 'a');  // compile-time error

You can substitute only non-primitive types for the type parameters K and V:

Pair<Integer, Character> p = new Pair<>(8, 'a');

Note that the Java compiler autoboxes 8 to Integer.valueOf(8) and 'a' to Character('a'):

Pair<Integer, Character> p = new Pair<>(Integer.valueOf(8), new Character('a'));

For more information on autoboxing, see Autoboxing and Unboxing in the Numbers and Strings lesson.

Cannot Create Instances of Type Parameters

You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:

public static <E> void append(List<E> list) {
    E elem = new E();  // compile-time error
    list.add(elem);
}

As a workaround, you can create an object of a type parameter through reflection:

public static <E> void append(List<E> list, Class<E> cls) throws Exception {
    E elem = cls.newInstance();   // OK
    list.add(elem);
}

You can invoke the append method as follows:

List<String> ls = new ArrayList<>();
append(ls, String.class);

             5、数组不能使用泛型:原因都是Object'类型,使用容易引起非具体类型问题。

             6、不能进行重载函数,当擦除原始函数相同时。

            7、Cannot Create, Catch, or Throw Objects of Parameterized Types

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值