在Java中使用递归从ArrayList中分离偶数和奇数索引,可以按照以下步骤进行操作:
public static ArrayList[] separateEvenOdd(ArrayList<Integer> list) {
ArrayList<Integer> evenList = new ArrayList<>();
ArrayList<Integer> oddList = new ArrayList<>();
separateEvenOddHelper(list, evenList, oddList, 0);
return new ArrayList[]{evenList, oddList};
}
private static void separateEvenOddHelper(ArrayList<Integer> list, ArrayList<Integer> evenList, ArrayList<Integer> oddList, int index) {
if (index >= list.size()) {
return;
}
if (index % 2 == 0) {
evenList.add(list.get(index));
} else {
oddList.add(list.get(index));
}
separateEvenOddHelper(list, evenList, oddList, index + 1);
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
ArrayList[] result = separateEvenOdd(list);
System.out.println("偶数索引的元素:" + result[0]);
System.out.println("奇数索引的元素:" + result[1]);
}
这样,就可以通过递归方法从ArrayList中分离偶数和奇数索引的元素。
领取专属 10元无门槛券
手把手带您无忧上云