简体   繁体   中英

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

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?

           //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);

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM