user1899174
user1899174

Reputation: 279

Trying to convert array of ints to a list

I'm trying to convert an array of type int to a List by doing

List<Integer> endingRoutesBusStopsList = Arrays.asList(endingRoutesBusStops);

but for some reason I keep getting an error saying

Type mismatch: cannot convert from List<int[]> to List<Integer>

I don't understand what the issue is.

I know doing

List<int[]> endingRoutesBusStopsList = Arrays.asList(endingRoutesBusStops);

will solve the error, but then I can't use it the way I want.

Anyone have any ideas?

Upvotes: 0

Views: 180

Answers (3)

Miquel
Miquel

Reputation: 15675

We are missing some more of your code, but in general, let me try and answer with code:

This works:

Integer[] arrayOfInt = { Integer.valueOf(0), Integer.valueOf(1) };
List<Integer> listOfInt = Arrays.asList(arrayOfInt);

This works too because the primitive "1" is autoboxed to an Integer object:

Integer[] arrayOfInt = { 1, 2, 3, 4 };
List<Integer> listOfInt = Arrays.asList(arrayOfInt);

Finally, this won't work because an int[] cannot be autoboxed to Integer[]:

int[] arrayOfInt = { 1, 2, 3, 4 };
List<Integer> listOfInt = Arrays.asList(arrayOfInt);

UPDATE: this comes from way down in the comments in a discussion with @MichaelBorek . This example repeatedly tries the same code either autoboxing or not. The cost of autoboxing seems to be that the code that uses it takes 5 times longer than the one that uses Objects directly.

Upvotes: 0

Michal Borek
Michal Borek

Reputation: 4624

The issue is because an "int[]" is an Object,

Arrays.asList(T...) gets generic vararg, that it means it treats "int[]" as "Object" (the common superclass for array int[] and Integer is Object)

so that from asList method perspective you don't pass an array of ints, but you pass an object .

In any way you should make implicit convertion from int to wrapper Integer. It is advisable to make it explicitly.

Upvotes: 2

zw324
zw324

Reputation: 27180

This is caused by the fact that int[] is different from Integer[]. Autoboxing does not work on Arrays.

Upvotes: 2

Related Questions