动态遍历ArrayList并添加每个第n个元素的方法可以通过以下步骤实现:
以下是一个示例代码:
import java.util.ArrayList;
public class DynamicArrayListTraversal {
public static void main(String[] args) {
ArrayList<Integer> originalList = new ArrayList<>();
originalList.add(1);
originalList.add(2);
originalList.add(3);
originalList.add(4);
originalList.add(5);
int n = 2; // 添加每个第2个元素
ArrayList<Integer> resultList = traverseAndAdd(originalList, n);
System.out.println("结果ArrayList: " + resultList);
}
public static ArrayList<Integer> traverseAndAdd(ArrayList<Integer> originalList, int n) {
ArrayList<Integer> resultList = new ArrayList<>();
for (int i = 0; i < originalList.size(); i++) {
if ((i + 1) % n == 0) {
resultList.add(originalList.get(i));
}
}
return resultList;
}
}
输出结果为:
结果ArrayList: [2, 4]
在这个例子中,原始ArrayList为[1, 2, 3, 4, 5],我们添加每个第2个元素,所以结果ArrayList为[2, 4]。
腾讯云相关产品和产品介绍链接地址:
请注意,以上链接仅供参考,具体产品选择应根据实际需求和情况进行评估。
领取专属 10元无门槛券
手把手带您无忧上云