Copying the first half of an ArrayList

前端 未结 4 1981
野性不改
野性不改 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:02
    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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-14 09:13

    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:

    • Even: If the size is even, then n / 2 is the correct size to chunk by.
    • Odd: If the size is odd, then you need to add 1 to the result for the odd-length list to have the middle value.
    0 讨论(0)
  • 2021-01-14 09:13

    Another approach:

    List<Integer> firstHalf = al.subList(0, al.size()/2 + (al.size()%2) - 1);
    
    0 讨论(0)
提交回复
热议问题