What is wrong here? I get a java.lang.ClassCastException error but I can't see where I have gone wrong

后端 未结 2 1116
遇见更好的自我
遇见更好的自我 2021-01-25 09:50

This is the first time I have really used Lists and Queues so this might be a very simple mistake. Is it because my queue is full of objects that can\'t be cast to integers?

相关标签:
2条回答
  • 2021-01-25 10:13

    My guess is that the issue is here:

    Arrays.asList(numberarray);
    

    If numberarray is an int[] rather than an Integer[], then that call will actually return a List of int[]s containing that array as one element.

    The ClassCastException happens later when you try to cast the int[] object to an Integer.

    Since Java doesn't support primitive collections there is no easy way to use Arrays.asList to wrap a primitive array - autoboxing doesn't work en masse like that. It's best to start off using an Integer[] if you plan to use it to back a Collection.

    Part of the confusion comes from the fact that the method asList(T...) takes varargs. If it just took a T[] as an argument instead, the compiler wouldn't let you pass in an int[] since primitive arrays don't extend Object[]. But with varargs support, the compiler infers T as int[] and thinks you mean to build a List backed by a single-element int[][].

    As others have noted, the use of generics will really help you out with ambiguities like this and it's always a good idea to program using them:

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

    This line gives the following compile error, instead of allowing your code to fail at runtime:

    incompatible types
    required: java.util.List<java.lang.Integer>
    found: java.util.List<int[]>

    Side note: Assuming you move to using an Integer[] don't forget that this means elements can now be null. Should this be the case a NullPointerException will be thrown when you unbox back to int - just be careful to ensure your implementation doesn't allow null elements or else check for null before unboxing.

    0 讨论(0)
  • 2021-01-25 10:16

    You really should use Generics and ArrayList/ArrayDeque unless it's really performance critical and you use a lot of atomic types like int. Then you should have a look at http://labs.carrotsearch.com/hppc.html

    0 讨论(0)
提交回复
热议问题