【问题标题】:What is wrong here? I get a java.lang.ClassCastException error but I can't see where I have gone wrong这里有什么问题?我收到 java.lang.ClassCastException 错误,但看不到哪里出错了
【发布时间】:2012-05-20 18:49:40
【问题描述】:

这是我第一次真正使用列表和队列,所以这可能是一个非常简单的错误。是因为我的队列中充满了无法转换为整数的对象吗?

           //populate array
        for(int i=0; i<11; i++){
            numberarray[i] = i; 
        }
        // populate list with numbers from array
        List numList = Arrays.asList(numberarray);
        Collections.shuffle(numList);

        Queue queue = new LinkedList();
        queue.addAll(numList);

        int num1 = (Integer) queue.poll();
        assignPictures(button01, num1);

【问题讨论】:

  • 您得到的ClassCastException 是什么?为什么不使用泛型来确保类型安全?
  • java.util.Arrays$ArrayList 不能转换为 java.lang.Integer...泛型是指 List
  • 我的意思是List&lt;Integer&gt;。基元不能用作类型参数
  • 谢谢.. 我尝试使用 List 而不是 List

标签: java arraylist queue classcastexception


【解决方案1】:

我的猜测是问题出在这里:

Arrays.asList(numberarray);

如果numberarrayint[] 而不是Integer[],则该调用实际上将返回int[]s 中的List,其中包含该数组作为一个元素。

ClassCastException 稍后会在您尝试将 int[] 对象强制转换为 Integer 时发生。

由于 Java 不支持原始集合,因此没有简单的方法可以使用 Arrays.asList 来包装原始数组 - 自动装箱不能像那样en masse 工作。如果您打算用它来支持Collection,最好先使用Integer[]

部分困惑来自asList(T...) 方法采用varargs。如果它只是将T[] 作为参数,编译器不会让你传入int[],因为原始数组不会扩展Object[]。但是在可变参数支持下,编译器将T 推断为int[],并认为您的意思是构建一个由单个元素int[][] 支持的List

正如其他人所指出的,使用 generics 确实可以帮助您解决此类歧义,使用它们进行编程总是一个好主意:

List<Integer> numList = Arrays.asList(numberarray);

这一行给出了以下编译错误,而不是让您的代码在运行时失败:

incompatible types
required: java.util.List&lt;java.lang.Integer&gt;
found: java.util.List&lt;int[]&gt;

旁注:假设您转而使用Integer[],不要忘记这意味着元素现在可以是null。如果是这种情况,当您取消装箱回int 时会抛出NullPointerException - 请注意确保您的实现不允许null 元素,否则在取消装箱前检查null

【讨论】:

  • 你是对的..我再次运行它并得到.. int[] cannot be cast to java.lang.Integer
  • 感谢旁注。我认为在我的 android 设备上测试了几次并查看了我的代码后,我的实现不允许在队列末尾使用 null 元素。谢谢这篇文章真的帮助了我!
  • @ConnorAtherton - 很高兴我能帮上忙!
【解决方案2】:

你真的应该使用泛型和 ArrayList/ArrayDeque,除非它对性能非常关键,并且你使用了很多原子类型,比如 int。那你应该看看 http://labs.carrotsearch.com/hppc.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多