30

Possible Duplicate:
How to create ArrayList (ArrayList<T>) from array (T[]) in Java

How to implement this method:

List<Integer> toList(int[] integers) {
    ???
    //return Arrays.asList(integers); doesn't work
}
Community
  • 1
  • 1
Roman
  • 59,060
  • 84
  • 230
  • 322

6 Answers6

7

There's probably a built-in method to do it somewhere* (as you note, Arrays.asList won't work as it expects an Integer[] rather than an int[]).

I don't know the Java libraries well enough to tell you where that is. But writing your own is quite simple:

public static List<Integer> createList(int[] array) {
    List<Integer> list = new ArrayList<Integer>(array.length);
    for (int i = 0; i < array.length; ++i) {
        list.add(array[i]);
    }
    return list;
}

Obviously one downside of this is that you can't do it generically. You'll have to write a separate createList method for each autoboxed primitive type you want.

*And if there isn't, I really wonder why not.

Dan Tao
  • 119,009
  • 50
  • 280
  • 431
  • For efficiency's sake, i might recommend `new ArrayList(array.length)`. Should keep Java from having to resize the collection to add elements. – cHao Jul 08 '11 at 17:13
2
List<Integer> asList(final int[] integers) {
    return new AbstractList<Integer>() {
        public Integer get(int index) {
            return integers[index];
        }

        public int size() {
            return integers.length;
        }
    };
}
ordnungswidrig
  • 3,068
  • 1
  • 15
  • 29
Christoffer Hammarström
  • 24,236
  • 4
  • 44
  • 54
  • 1
    There are a couple of big issues: (1) the list is backed by the array -- that is, if the array elements change, the list elements will too. (2) For larger ints, you'll get back a different Integer each time -- that is, you can not have any expectation of reference equality. Either of those might or might not be an issue, but they're semi-surprising behavior. Before i add (3), can Java actually do closures like that? – cHao Jul 08 '11 at 16:42
  • @cHao: 3. Yes, Java can do closures like that! – Alexander Pogrebnyak Jul 08 '11 at 16:45
  • 1
    Technically this should then be named **as** List, at least when assuming that Java follows the same naming convention as .NET in this regard (*as* providing a differently-typed view on the same collection while *to* actually doing a conversion). – Joey Jul 08 '11 at 16:51
  • 2
    These are not closures. They are anonymous classes. – Senthess Jul 08 '11 at 16:57
  • Just to add one more thing: whenever you are accessing this `List`, conversion from _`int` to `Integer`_ happens which is very slow. Don't do what this answer is recommending – Op De Cirkel Jul 08 '11 at 16:58
  • @Senthess: It's an anonymous class with methods that refer to a local variable from the context it's created in. That's pretty much the definition of a closure, at least in the way Java could do it. – cHao Jul 08 '11 at 17:01
  • invoking `addAll(...)` on such a list and then `get(...)` would result in odd behavior since `get(...)` only is able to access the numbers from the `int[]`. In short: although it looks neat, I wouldn't recommend doing it like this. – Bart Kiers Jul 08 '11 at 17:11
  • I remember when I saw this for the first time in Java. It's kind of sad, actually: they decided to do *big*-time support for anonymous classes, allowing you to implement an entire interface on the fly. But it involves so much typing that doing simple stuff like a one-line C#-style lambda isn't possible. – Dan Tao Jul 08 '11 at 17:12
  • @Op De Cirkel: That depends on the use. This will be faster if not all Integers in the list are accessed. And in most cases the performance difference will be too small to matter anyway. – Christoffer Hammarström Jul 10 '11 at 15:47
  • @cHao: That it's backed by the array is a much a feature as an issue. It depends on the use. – Christoffer Hammarström Jul 10 '11 at 15:58
  • @Bart Kiers: This list does not support `addAll()`, since `AbstractList#set(int, Integer)` is not overridden, so no, it would not result in odd behaviour. The behaviour is well-defined. That the list should be modifiable wasn't a requirement, and it might be considered a feature that it's not, depending on the use. – Christoffer Hammarström Jul 10 '11 at 15:58
  • Also, `AbstractList#add(int, Integer)` – Christoffer Hammarström Jul 10 '11 at 16:06
  • 1
    @Christoffer, ah, yes, then there's no problem: I thought `add(...)` was implemented in `AbstractList`. My bad, thanks for the info! – Bart Kiers Jul 10 '11 at 16:30
2

Use commons-lang3 org.apache.commons.lang3.ArrayUtils.toObject(<yout int array>) and then java.util.Arrays.asList(<>)

ArrayUtils.toObject() will copy the array, and Array.asList() will simply create list that is backed by new array.

int[] a = {1, 2, 3};
List<Integer> aI = Arrays.asList(ArrayUtils.toObject(a));

EDIT: This wont work if you want to add() new elements (resize) though the list interface, if you want to be able to add new elements, you can use new ArrayList(), but this will create one more copy.

Op De Cirkel
  • 26,245
  • 6
  • 37
  • 52
  • You can do it directly with `List xValues = Arrays.asList(new Integer[] { 150, 160, 175, 165, 165 });` – Alexander Pacha Jan 14 '13 at 21:23
  • @AlexanderPacha Definitely, it works with an `Integer[]` literal, but not with an existing `int[]`. It can not be placed in the method skeleton from the OP. – Dávid Horváth Nov 13 '18 at 09:35
1
List<Integer> toList(int[] integers) {
    // Initialize result's size to length of the incoming array
    // this way it will not require reallocations
    ArrayList<Integer> result = new ArrayList<Integer>( integers.length );

    for ( int cur: integers )
    {
        result.add( Integer.valueOf( cur ) );
    }

    return result;
}
Alexander Pogrebnyak
  • 42,921
  • 9
  • 97
  • 117
0

I do not think there is a quick way to do it unfortunately. I believe you will have to iterate the array and add it one by one.

Oscar Gomez
  • 18,102
  • 12
  • 80
  • 113
0
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

public class Listing {
  public static void main(String[] args) {

   int[] integers = {1,2,3,4};

   java.util.List<Integer> list = new ArrayList<Integer>();
  for (int i=0; i< integers.length; i++)
  {
      list.add(integers[i]);
  }
  System.out.println(list);
}
}

Tested and working as expected!

glarkou
  • 6,635
  • 11
  • 62
  • 112