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

后端 未结 5 637
萌比男神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-29 00:05

    Do you like this solution?

    public static void main(final String[] args) {
        ArrayList numbers = new ArrayList();
        numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40);
        //numbers.add(50); numbers.add(60); numbers.add(70);
    
        ArrayList numbers2 = new ArrayList();
        numbers2.add(4); numbers2.add(5); numbers2.add(6); numbers2.add(7);
        numbers2.add(8); numbers2.add(9); numbers2.add(10); numbers2.add(11);
    
        System.out.println("list1: " + numbers);
        System.out.println("list2: " + numbers2);
        List interleaved = interleave(numbers, numbers2);
    
        System.out.println("\nCombined: " + interleaved);
    }
    
    public static List interleave(
        final List list1,
        final List list2
    ) {
        List result
            = new ArrayList(list1.size() + list2.size());
    
        Iterator it1 = list1.iterator();
        Iterator it2 = list2.iterator();
        while (it1.hasNext() || it2.hasNext()) {
            if (it1.hasNext()) {
                result.add(it1.next());
            }
            if (it2.hasNext()) {
                result.add(it2.next());
            }
        }
        return result;
    }
    

提交回复
热议问题