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

后端 未结 5 638
萌比男神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:57

    A few comments:

    • I would probably have returned a new List instead of arbitrarily modifying one of them
    • The new algorithm is then simpler:
      • create a new empty list
      • loop on a counter from 0 to the min of the two lists' sizes and interleave
      • when you are done, check if one of the lists has more items and add them (for example with a combination of addAll and subList)
      • return the list
    • If you don't need to mutate the two original lists, you can declare them in a shorter way with: List numbers = Arrays.asList(10, 20, 30, 40); - note that it creates a fixed-size list so you can't add or remove
    • With your current code, instead of duplicating things you could have something like: List listSmall, listBig; if (list1.size() < list2.size()) { listSmall = list1; listBig = list2; } else { /* the opposite */} - then you know that listSmall is the small one and you only need one loop.

提交回复
热议问题