0

This is my code so far. I'm kind of new with ArrayLists.

public void fill(int []arr){
   ArrayList<Integer> intList = new ArrayList<Integer>();
}

Thats all I have so far. I don't know how to put all of the elements from int[] arr into the new ArrayList. The elements should be in order as well.

Leigh
  • 28,765
  • 10
  • 55
  • 103
user1261935
  • 23
  • 3
  • 5

3 Answers3

3

If you had an array of objects, you could use Arrays.asList ..., but with primitives, you'll have to loop through the array and add each element to the arraylist individually.

for (int i : arr) {
    intList.add(i);
}
JRL
  • 76,767
  • 18
  • 98
  • 146
3
List<Integer> list = Arrays.asList(myIntArray);

Otherwise, you will need to use a loop and iterate over the array.

Tyler Treat
  • 14,640
  • 15
  • 80
  • 115
0

This should do the job.

public void fill(int []arr){
   ArrayList<Integer> intList = new ArrayList<Integer>();
   for(int i = 0; i < arr.length; i++) {
      intList.add(arr[i])
   }
}

Also refer to the ArrayList JavaDoc.

alex
  • 4,922
  • 7
  • 37
  • 51