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.
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.