Copying the first half of an ArrayList

前端 未结 4 1980
野性不改
野性不改 2021-01-14 08:53

There is an ArrayList al, and I want to copy the first half of its elements into another ArrayList firstHalf. (If al

4条回答
  •  一整个雨季
    2021-01-14 09:11

    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

提交回复
热议问题