Copying the first half of an ArrayList

arraylist, java

Solution

You should use `add` instead of `set`:

int x = al.size()/2 + (al.size()%2) - 1;
for(int i = 0; i < x; i++){
    firstHalf.add(al.get(i));
 }

It would be better to use List#subList

Problem

There is an `ArrayList<Integer> al`, and I want to copy the first half of its elements into another `ArrayList<Integer> firstHalf`. (If al has an odd number of elements, `firstHalf` should have one more element.) However, the following code throws an `IndexOutOfBoundsException`, and says `Index: 0, Size: 0`, though I'm not sure how that would be a problem, since the indices of ArrayLists start at 0. Also, I am aware of `.arraycopy`, but I would like to do it this way, with for-loops. ``` int x = al.size()/2 + (al.size()%2) - 1; for(int i = 0; i < x; i++){ firstHalf.set(i, al.get(i)); } ```

Original source