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.
--
Adam Monsen
Tom Hawtin - 19 May 2007 22:21 GMT
> 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
Roedy Green - 20 May 2007 05:54 GMT
>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.
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Adam Monsen - 20 May 2007 19:10 GMT
Thanks Tom, Roedy, that helps.
It appears I'm not the only confused soul:
http://forum.java.sun.com/thread.jspa?messageID=9673344
--
Adam Monsen