How do i convert array to ArrayList?

Please i need to know

There are many ways to do it. 1 to them is to use java.util.Arrays.asList().
Then you can use that returned fixed-size List as the passed argument for a new ArrayList.

1 Like

manual


int [] arr1 = {
  33,
  23,
  11
};

ArrayList<Integer>  arrList;

arrList = new ArrayList();

for (int n = 0; n < arr1.length; n++) {
  arrList.add( arr1[n] );
}

arr1=null;

for (int i : arrList) {
  println(i);
}


2 Likes

gotoLoop’s way

unfortunately, in the for loop at the end I wasn’t able to say

for (Integer i : arrList) {
import java.util.*;


int [] arr1 = {
  33,
  23,
  11
};

ArrayList<Integer> arrList;

size(660, 660);

arrList = new ArrayList(Arrays.asList(arr1));

//for (int n = 0; n < arr1.length; n++) {
//  arrList.add( arr1[n] );
//}

arr1=null;

for (Object i : arrList) {
  println(i);
}
//

2 Likes

For arrays of primitive type such as int[], asList() won’t work.

A manual approach like yours would be OK then:

final int[] arr = { 10, 20, 30 };
final ArrayList<Integer> arrList = new ArrayList<Integer>(arr.length);

for (final int num : arr) arrList.add(num);

println(str(arr));
println(arrList);

exit();
3 Likes