我为以下场景做了很多工作,但我无法获得所需的输出。
我陷入了以下情况:
Arraylist1 = {10,20,30};
Arraylist2 = {4,5,7}
我希望输出为:
Combined: [10, 4, 10, 5, 10, 7, 20, 4, 20 ,5, 20, 7, 30, 4, 30, 5, 30, 7]
我所做的一切如下:
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(10); numbers.add(20); numbers.add(30); numbers.add(40);
ArrayList<Integer> numbers2 = new ArrayList<Integer>();
numbers2.add(4); numbers2.add(5); numbers2.add(7);
List<Integer> interleaved = interleave(numbers, numbers2);
System.out.println("\nCombined: " + interleaved);
public static List<Integer> interleave(final List<Integer> list1, final List<Integer> list2) {
List<Integer> result = new ArrayList<Integer>(list2.size() + list1.size());
Iterator<Integer> it1 = list1.iterator();
Iterator<Integer> it2 = list2.iterator();
while (it1.hasNext() || it2.hasNext()) {
if (it1.hasNext()) {
result.add(it1.next());
}
if (it2.hasNext()) {
result.add(it2.next());
}
}
return result;
}
但我得到的输出是
Combined: [10, 4, 20, 5, 30, 7]
我希望输出像
Combined: [10, 4, 10, 5, 10, 7, 20, 4, 20 ,5, 20, 7, 30, 4, 30, 5, 30, 7]