问题
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);
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/10676185/what-is-wrong-here-i-get-a-java-lang-classcastexception-error-but-i-cant-see-w