Java: Interleave two integer based arraylists -> good approach?

后端 未结 5 677
萌比男神i
萌比男神i 2021-01-28 23:18

Homework: Looking for better strategy, or approach rather than complete code.

I\'v got two arrayLists of integers under two conditions:

  1. th
5条回答
  •  甜味超标
    2021-01-28 23:54

    I propose the following code:

    private static List joinTwoLists(List a, List b) {
        final boolean aIsBigger = a.size() > b.size();
        final List joined = new ArrayList<>(aIsBigger ? a : b);
        final AtomicInteger index = new AtomicInteger(1);
        for (Integer value : aIsBigger ? b : a) {
            joined.add(index.getAndAdd(2), value);
        }
        return joined;
    }
    

提交回复
热议问题