day07-常用类-ArrayList-练习2

This commit is contained in:
2026-05-16 11:15:42 +08:00
parent 9a9e6a53bf
commit 55ad571736

View File

@@ -1,8 +1,55 @@
package com.inmind.arraylist03;
import java.util.ArrayList;
/*
常用类_ArrayList_练习4_获取偶数集合
有一个原本的集合该集合中有正整数1,3,4,5,8,9
将集合中的偶数都取出来,保存,奇数不要
*/
public class Test13 {
public static void main(String[] args) {
//1.定义数据
ArrayList<Integer> integers = new ArrayList<>();
integers.add(2);
integers.add(3);
integers.add(3);
integers.add(4);
integers.add(8);
integers.add(6);
//2.调用方法,打印只有偶数的集合
// getOushu(integers);
getOushu1(integers);
}
//实现方式二:直接将原集合中的奇数删除即可
public static void getOushu1(ArrayList<Integer> lists) {
//遍历集合判断是奇数就删除remove
for (int i = 0; i < lists.size(); i++) {
Integer value = lists.get(i);
if (value % 2 != 0) {//自动拆箱
lists.remove(i);
i--;//注意但凡在集合遍历中删除一定要加i--,避免跳过元素
}
}
System.out.println(lists);
}
//实现方式一:重新创建一个新的集合,遍历原集合,判断是偶数则添加到新集合
public static void getOushu(ArrayList<Integer> lists) {
ArrayList<Integer> newLists = new ArrayList<>();
//遍历原集合,判断是偶数则保存到新集合
for (int i = 0; i < lists.size(); i++) {
Integer value = lists.get(i);
if (value % 2 == 0) {//自动拆箱
newLists.add(value);
}
}
System.out.println(newLists);
}
}