用一个大集合,添加二十个随机数,将数组中的偶数找到并添加到一个小集合中

 1 import java.util.ArrayList;
 2 import java.util.Random;
 3 
 4 /**
 5  * 用一个大集合,添加二十个随机数,将数组中的偶数找到并添加到一个小集合中
 6  * */
 7 public class C10__ArrayListTest {
 8     public static void main(String[] args) {
 9         // 创建结合对象
10         ArrayList<Integer> list1 = new ArrayList<>();
11         ArrayList<Integer> list2 = new ArrayList<>();
12 
13         // 添加数据
14         addNum(list1);
15         // 调用方法,将偶数添加到小集合中
16         returnNum(list1,list2);
17         System.out.println(list2);
18     }
19 
20     // 集合添加对象
21     public static void addNum(ArrayList<Integer> array){
22         // 创建随机数对象
23         Random random = new Random();
24         for (int i = 0; i < 20; i++) {
25             // 将产生的对象添加到大集合中
26             array.add(random.nextInt());
27         }
28     }
29 
30     // 将偶数添加到小集合
31     public static void returnNum(ArrayList<Integer> list1,ArrayList<Integer> list2 ){
32         for (int i = 0; i < list1.size(); i++) {
33             int num = list1.get(i);
34             // 判断是否是偶数
35             if(num % 2 == 0){
36                 // 偶数添加到小集合中
37                 list2.add(num);
38             }
39         }
40     }
41 }

猜你喜欢

转载自www.cnblogs.com/BRIGHTM00N/p/10494684.html