引发ClassCast异常

时间:2014-11-08 05:22:21

标签: java exception

    int [] arr =  {1,2,4,3,6,3,2,9};
    Collection<Integer> c = new HashSet<Integer>((Collection)Arrays.asList(arr));

    for(int x : c)
    {
        System.out.print(x);
    }

上面的代码抛出了一个classcast异常。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:5)

Arrays.asList获取一组对象Object[])。 int不是对象,这意味着无法将int[]解释为Object[] - 要做到这一点,arr必须是Integer[]。 (永远记住原语和对象根本不同,即使编译器有时会方便地在它们之间进行转换。)

但是int[]本身一个对象。这意味着Arrays.asList(arr)可以使用varargs功能转向:

Arrays.asList(arr)

成:

Arrays.asList(new int[][] { arr })

这是一个单元素数组,其唯一元素是int[]类型 - 一个数组数组。

换句话说,Arrays.asList的输入被解释为单个对象(int[] arr),然后将其包装到一个单元素的对象数组中。因此结果类型为List<int[]>

然后您使用此List<int[]>并尝试将其转换为Collection<Integer>。这意味着当您获取第一个项目(int[])时,它会转换为Integer。这就是造成ClassCastException的原因。

相反,您应该直接使用varargs:

Arrays.asList(1, 2, 4, 3, 6, 3, 2, 9)

如果这样做,编译器别无选择,只能将每个元素视为一个对象。它会通过将每个人自动装入Integer来实现。最终结果是这样的:

Arrays.asList(new Integer[]{ Integer.valueOf(1), Integer.valueOf(2), ... })

作为一般建议,检查警告是有原因的。直到你非常对通用和擦除感到满意为止,我建议不要压制它们。 ClassCastException不会发生,直到你尝试从Collection<Integer>中取出一些东西,这可能比你把这些元素放入的时间要晚得多 - 而且可能在另一个类中完全。

答案 1 :(得分:0)

请不要使用raw types,请使用菱形运算符<>,不要尝试将原始数组添加到Collection中 -

Integer[] arr = { 1, 2, 4, 3, 6, 3, 2, 9 };
Collection<Integer> c = new HashSet<>(Arrays.asList(arr));

for (int x : c) {
    System.out.print(x);
}

问题在于

int[] arr;
Arrays.asList(arr);

返回List<int[]>