引发ClassCast异常 [英] ClassCast Exception being thrown

查看:94
本文介绍了引发ClassCast异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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异常。有人可以帮忙吗?

Above code is throwing classcast exception. Can anyone please help?

推荐答案

Arrays.asList 需要一个数组 objects Object [] )。 int 不是对象,这意味着不可能将您的 int [] 解释为 Object [] -为此, arr 必须为 Integer [] 。 (始终记住,即使编译器有时会为您方便地在它们之间进行转换,基元和对象也从根本上有所不同。)

Arrays.asList takes an array of objects (an Object[]). ints are not objects, which means it's impossible to interpret your int[] as an Object[] -- to do that, arr would have to be Integer[]. (Always remember that primitives and objects are fundamentally different, even if the compiler will sometimes conveniently convert between them for you.)

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

But int[] itself is an Object. That means Arrays.asList(arr) can use the varargs functionality to turn:

Arrays.asList(arr)

进入:

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

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

This is a single-element array, whose only element is of type int[] -- an array of arrays.

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

In other words, the input to Arrays.asList is interpreted as a single object (the int[] arr), which is then wrapped into a one-element array of objects. So the result type is List<int[]>.

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

You then take this List<int[]> and try to cast it to a Collection<Integer>. This means that when you fetch the first item (which is an int[]), it's cast to an Integer. That's what's causing your ClassCastException.

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

Instead, you should use the varargs directly:

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

如果这样做,编译器别无选择,只能将每个元素都视为一个对象。为此,需要将每个自动装箱到 Integer 中。最终结果是这样的:

If you do that, the compiler has no choice but to treat each element as an object. It'll do that by auto-boxing each one into an Integer. The end result is something like this:

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

作为一般建议,选中的警告为那里是有原因的。在您非常熟悉泛型和擦除之前,我建议您不要压制它们。除非您尝试从 Collection< Integer> 中获取某些内容,否则ClassCastException不会发生,这可能比将这些元素放入-并且可能放入时要晚得多。完全是另一堂课。

As a general piece of advice, the checked warnings are there for a reason. Until you become very comfortable with generics and erasures, I would recommend not suppressing them. The ClassCastException doesn't happen until you try to fetch something out of the Collection<Integer>, which could happen much later than when you put those elements in -- and possibly in another class altogether.

这篇关于引发ClassCast异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆