java 数组协变_java 数组的协变和逆变

先说结论:

基元类型数组不允许协变和逆变,无法编译通过。

引用类型数组允许协变和逆变,逆变时会检查实际类型,如果不相符则抛出java.lang.ClassCastException。

下面是验证代码。

1 public classTestArrayInstance {2 public static voidmain(3 String[] args4 ) {5 char[] a1 = {'1', '2', '3'};6 int[] a2 = {1, 2, 3};7 long[] a3 = {1L, 2L, 3L};8 float[] a4 = {1.0F, 2.0F, 3.0F};9 double[] a5 = {1.0, 2.0, 3.0};10 Integer[] a6 = {1, 2, 3};11 Long[] a7 = {1L, 2L, 3L};12

13 String[] a8 = {"1", "2", "3"};14 Object[] a9 = {"1", 2L, 3};15

16 printCheck(a1, Character[].class);17 printCheck(a1, Object[].class);18 printCheck(a2, Integer[].class);19 printCheck(a2, Object[].class);20 printCheck(a2, Long[].class);21 printCheck(a2, long[].class);22 printCheck(a3, Long[].class);23 printCheck(a3, double[].class);24 printCheck(a4, Float[].class);25 printCheck(a4, Double[].class);26 printCheck(a4, double[].class);27 printCheck(a5, Double[].class);28 printCheck(a6, Long[].class);29 printCheck(a6, int[].class);30 printCheck(a6, long[].class);31 printCheck(a7, Double[].class);32 printCheck(a7, long[].class);33 printCheck(a7, int[].class);34 printCheck(a8, Object[].class);35 printCheck(a9, String[].class);36 }37

38 private static voidprintCheck(39 Object v,40 Class>c41 ) {42 System.out.println(paddingClassName(v.getClass()) + " instanceof " + paddingClassName(c) + (c.isInstance(v) ? " true" : " false"));43 }44

45 private staticString paddingClassName(46 Class>c47 ) {48 return (c.getSimpleName() + " ").substring(0, 12);49 }50 }

执行结果:

char[] instanceof Character[] false

char[] instanceof Object[] false

int[] instanceof Integer[] false

int[] instanceof Object[] false

int[] instanceof Long[] false

int[] instanceof long[] false

long[] instanceof Long[] false

long[] instanceof double[] false

float[] instanceof Float[] false

float[] instanceof Double[] false

float[] instanceof double[] false

double[] instanceof Double[] false

Integer[] instanceof Long[] false

Integer[] instanceof int[] false

Integer[] instanceof long[] false

Long[] instanceof Double[] false

Long[] instanceof long[] false

Long[] instanceof int[] false

String[] instanceof Object[] true

Object[] instanceof String[] false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值