Arrays.asList(int[]) result unexpected

A

Adam Monsen

I'm confused about the behavior of Arrays.asList(int[]). In the code
snippet below, the line commented with ERROR is the part I don't
understand... I would expect the number 2 wrapped in an Integer would
be returned when calling b.get(1), but instead I just get a generic
object.


import java.util.*;

class Test {
public static void main(String args[]) {
int[] a = {1,2,3};
System.out.println("int[]: " + a); // prints id

List b = Arrays.asList(a);
System.out.println("asList(): " + b); // prints [id]
// System.out.println(b.get(1)); // ERROR. ???

Integer[] c = {1,2,3};
System.out.println("Integer[]: " + c); // prints id

List d = Arrays.asList(c);
System.out.println("asList(): " + d); // prints [1,2,3]
System.out.println(d.get(1)); // prints 2
}
}


So, fine, perhaps Arrays.asList(int[]) isn't going to do what I want.
Is there a better one-shot way to convert int[] to List of Integer, or
do I just need to loop over int[] a and manually create a List, like
so?

int[] a = {1,2,3};
List ab = new ArrayList(a.length);
for (int z : a) ab.add(z);

It might just be me, but I sure feel like Arrays.asList(int[]) should
behave differently. What exactly does Arrays.asList(int[]) return?

And the fact that I could be doing Arrays.asList(1,2,3) doesn't really
help me unless there is an easy way to send int[] a as three arguments
instead of one.
 
T

Tom Hawtin

Adam said:
I'm confused about the behavior of Arrays.asList(int[]). In the code

Arrays.asList takes an array of references as its argument. int[] is not
an array of references. However, as int[] is a reference, the compiler
treats it the code as Arrays.asList(new int[][] { a }) (where a is an
int[]), which gives you a List<int[]> (which I believe is what the error
message should tell you, if you quoted it).

If you just want a copy of the array, convert the int[] to an Integer[]
or List<Integer> yourself. Of course that wont reflect changes to the
list in the int[]. To do that, you'll have to write you own List
implementation.

Tom Hawtin
 
R

Roedy Green

I'm confused about the behavior of Arrays.asList(int[]). In the code
snippet below, the line commented with ERROR is the part I don't
understand... I would expect the number 2 wrapped in an Integer would
be returned when calling b.get(1), but instead I just get a generic
object.

autoboxing will interconvert Integer and int transparently, but not
Integer[] and int[]. That you will have to do yourself element by
element.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top