0

I have an array int[] a = {1,2,3} I want to convert it to an ArrayList, and vice versa. These are my attempts but they don't work. Can someone point me in the right direction, please.

The following are my attempts below

public class ALToArray_ArrayToAL {
public static void main(String[] args) {
    ALToArray_ArrayToAL obj = new ALToArray_ArrayToAL();

    obj.populateALUsingArray();
}

public void populateArrayUsingAL()
{
    ArrayList<Integer> al = new ArrayList<>();
    al.add(1);al.add(2);al.add(3);al.add(4);

    /* Don't want to do the following, is there a better way */
    int[] a = new int[al.size()];
    for(int i = 0;i<al.size();i++)
        a[i] = al.get(i);

    /* This does not work either */
    int[] b = al.toArray(new int[al.size()]);
}

public void populateALUsingArray()
{
    /* This does not work, and results in a compile time error */
    int[] a = {1,2,3};
    ArrayList<Integer> al = new ArrayList<>(Arrays.asList(a));


    /* Does not work because I want an array of ints, not int[] */
    int[] b = {4,5,6};
    List list = new ArrayList(Arrays.asList(b));
    for(int i = 0;i<list.size();i++)
        System.out.print(list.get(i) + " ");
}

}

1 Answers1

1

Accept the inevitability of a for loop:

for (int i : array) {
  list.add(i);
}

...or use streams in Java 8, though frankly they're more of a pain than they're worth for this case:

Arrays.stream(array).boxed().collect(Collectors.toList())

...or use a third-party library like Guava and write

List<Integer> list = Ints.asList(array);
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413