day07-常用类-ArrayList-练习4_获取偶数集合
This commit is contained in:
@@ -1,12 +1,53 @@
|
|||||||
package com.inmind.arraylist03;
|
package com.inmind.arraylist03;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
常用类-ArrayList-练习4_获取偶数集合
|
常用类-ArrayList-练习4_获取偶数集合
|
||||||
*/
|
*/
|
||||||
public class Test14 {
|
public class Test14 {
|
||||||
//有一个集合,该集合中有正整数,1,3,4,5,8,9将集合中的偶数都取出来,保存,奇数不要
|
//有一个集合,该集合中有正整数,1,3,4,5,8,9将集合中的偶数都取出来,保存,奇数不要
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
//1.创建新集合方式,添加偶数
|
|
||||||
//2.在原集合的基础上,删除奇数
|
//2.在原集合的基础上,删除奇数
|
||||||
|
ArrayList<Integer> list = new ArrayList<Integer>();
|
||||||
|
list.add(1);
|
||||||
|
list.add(1);
|
||||||
|
list.add(2);
|
||||||
|
list.add(3);
|
||||||
|
list.add(4);
|
||||||
|
list.add(5);
|
||||||
|
list.add(8);
|
||||||
|
list.add(9);
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
Integer temp = list.get(i);//对应元素
|
||||||
|
if (temp % 2 != 0) {//是奇数就删除
|
||||||
|
list.remove(i);
|
||||||
|
//注意:在集合遍历中删除一个元素,索引位置前移一位,保证数据不跳过
|
||||||
|
i --;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.println(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
//方式一
|
||||||
|
public static void method1(String[] args) {
|
||||||
|
//1.创建新集合方式,添加偶数
|
||||||
|
ArrayList<Integer> list = new ArrayList<Integer>();
|
||||||
|
list.add(1);
|
||||||
|
list.add(3);
|
||||||
|
list.add(4);
|
||||||
|
list.add(5);
|
||||||
|
list.add(8);
|
||||||
|
list.add(9);
|
||||||
|
|
||||||
|
ArrayList<Integer> oushuList = new ArrayList<Integer>();
|
||||||
|
//遍历集合,取出每个元素,判断是否是偶数,是则添加到新集合中
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
Integer temp = list.get(i);
|
||||||
|
if (temp % 2 == 0) {
|
||||||
|
oushuList.add(temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.println(oushuList);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user