java 数组的协变和逆变
先说结论:
- 基元类型数组不允许协变和逆变,无法编译通过。
- 引用类型数组允许协变和逆变,逆变时会检查实际类型,如果不相符则抛出java.lang.ClassCastException。
下面是验证代码。
1 public class TestArrayInstance { 2 public static void main( 3 String[] args 4 ) { 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 void printCheck( 39 Object v, 40 Class<?> c 41 ) { 42 System.out.println(paddingClassName(v.getClass()) + " instanceof " + paddingClassName(c) + (c.isInstance(v) ? " true" : " false")); 43 } 44 45 private static String paddingClassName( 46 Class<?> c 47 ) { 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