day07-常用类-ArrayList-练习2
This commit is contained in:
@@ -1,8 +1,55 @@
|
|||||||
package com.inmind.arraylist03;
|
package com.inmind.arraylist03;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
常用类_ArrayList_练习4_获取偶数集合
|
常用类_ArrayList_练习4_获取偶数集合
|
||||||
有一个原本的集合,该集合中有正整数,1,3,4,5,8,9
|
有一个原本的集合,该集合中有正整数,1,3,4,5,8,9
|
||||||
将集合中的偶数都取出来,保存,奇数不要
|
将集合中的偶数都取出来,保存,奇数不要
|
||||||
*/
|
*/
|
||||||
public class Test13 {
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user