3

Consider this code:

int[] tcc = {1,2,3};
ArrayList<Integer> tc = Arrays.asList(tcc);

For the above, Java complains that it cannot convert from List<int[]> to ArrayList<Integer>.

What's wrong with this?

Why is it List<int[]> and not List<int>?

3 Answers 3

3

An ArrayList can hold only objects not primitives such as ints, and since int != Integer you can't do what you're trying to do with an array of primitives, simple as that. This will work for an array of Integer though.

Sign up to request clarification or add additional context in comments.

2 Comments

He could also do: Arrays.asList(1, 2, 3);
It is called autoboxing, combined with the varargs syntax ... so in fact you are creating an array of Integer here.
1

This will work:

ArrayList tc = new ArrayList(Arrays.asList(1,2,3));

1 Comment

Maybe I'm mislooking something but I can't see the point. Assume I get an int[] parameter; what do I do with that?
1

You could have it as:

List<int[]> tc = Arrays.asList(tcc);

Arrays.asList returns a List, not an ArrayList. And since Arrays.asList is a varargs function, it thinks tcc is one element of a bigger array.

If you want to have just a List of Integers, you'd have to rewrite it as SB mentioned in the comments for Hovercraft Of Eel's answer:

List<Integer> tc = Arrays.asList(1, 2, 3);

Alternatively, if you make tcc an Integer[], you can still use your array as an argument in the following snippet by explicitly asking for a List of Integer, providing a type parameter that agrees with the passed array:

 Integer[] tcc = {1,2,3};
 List<Integer> tc = Arrays.<Integer>asList(tcc);

1 Comment

so what if you have an int[] parameter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.