There is an ArrayList
, and I want to copy the first half of its elements into another ArrayList
. (If al
List<Integer> firstHalf = al.subList(0, (int) al.size() / 2 + 1);
Is easier convert the al.size() / 2 to integer than doing "%2".
You add 1 to firstHalf to be bigger than the second half.
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
List#subList is exactly suited for this purpose.
int chunkSize = al.size() % 2 == 0 ? al.size() / 2 : (al.size() / 2) + 1;
List<Integer> firstHalf = al.subList(0, chunkSize);
There are two cases to consider:
Another approach:
List<Integer> firstHalf = al.subList(0, al.size()/2 + (al.size()%2) - 1);