1

Possible Duplicates:
Arrays.asList() not working as it should?
How to convert int[] into List<Integer> in Java?

Or must I refactor int[] to Integer[] ?

Community
  • 1
  • 1
bltc
  • 371
  • 1
  • 3
  • 9

5 Answers5

2
  1. You can't have List<int>

  2. Arrays.asList(array); will return you List with type T of (passed array)

You can have something like

  Integer[] a = new Integer[]{1,2,3};
  List<Integer> lst = Arrays.asList(a);
jmj
  • 237,923
  • 42
  • 401
  • 438
2

You can do this way

Integer[] a ={1,2,4};

List<Integer> intList =  Arrays.asList(a);

System.out.println(intList);
1

Arrays.asList(array) returns a List-type view on the array. So you can use the List interface to access the values of the wrapped array of java primitives.

Now what happens if we pass an array of java Objects and an array of java primitive values? The method takes a variable number of java objects. A java primitive is not an object. Java could use autoboxing to create wrapper instances, but in this case, it will take the array itself as an java object. So we end up like this:

List<Integer> list1 = Arrays.asList(new Integer[]{1,2,3}));
List<int[]>   list2 = Arrays.asList(new int[]{1,2,3}));

The first collection holds the integer values, the second one the int[] array. No autoboxing here.

So if you want to convert an array of java primitives to a List, you can't use Arrays.asList, because it will simply return a List that contains just one item: the array.

Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
0

EDIT :

From the comment below from develman, java 6 has support to return List<> object for same method

OLD ANSWER :

Arrays.asList(array) returns you a java.util.List object.

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
  • 1
    Java6 does it. Check current API: http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...) – Georg Leber Jan 25 '11 at 10:20
0

If you have a array of Integers then you can use Arrays.asList() to get a List of Integers:

Integer[] inters = new Integer[5];
List<Integer> ints = Arrays.asList(inters);
Georg Leber
  • 3,470
  • 5
  • 40
  • 63