Use ArrayList as the return value type
topic: use a large collection to store 20 random numbers, and then filter the even-numbered elements among them, and place them in a small collection.
Use a custom method to achieve
analysis:
1. You need to create a large collection, use To store int numbers, <Integer>
2. Random numbers use Random nextInt ()
3. Loop 20 times, hit random numbers into a large collection: for loop, add method
4. Define a method for
screening: the base is large Collection, filter the elements that meet the requirements, get a small collection
Three elements:
return value type: ArrayList small collection (the number of elements is uncertain)
Method name: getSmallList
parameter list: ArrayList large collection (with 20 random elements)
5. Judgment (if) is an even function: num% 2 == 0;
6. If it is even, put it in a small set, otherwise do n’t put it
import java.util.ArrayList;
import java.util.Random;
public class Text10ArrayListReturn {
public static void main(String[] args) {
//第一,先引入ArrayList与Random
ArrayList<Integer> bigList=new ArrayList<>();
Random r=new Random();
//第二,从1~100之间抽取20个数字 与add方法存储 然后用ArrayList<Integer> 作为返回值类型 及参数bigList
for(int i=0;i<20;i++) {
int num=r.nextInt(100)+1;//将随机的数字放入num 从100个数字中抽取20个数字
bigList.add(num);//将20个数字添加进去
//System.out.println(num);
}
ArrayList<Integer> sList = getSamllList(bigList);
//遍历出偶数
System.out.println("偶数个数"+sList.size());
for(int i=0;i<sList.size();i++) {
System.out.print("\t"+sList.get(i));
}
}
// 第三 这个方法,接受大集合参数,返回小集合结果
public static ArrayList<Integer> getSamllList(ArrayList<Integer> bigList){
//第四,创建个小集合 从大集合中20个数字筛选出偶数 也是用add方法
ArrayList<Integer> samllList=new ArrayList<>();
for(int i=0;i<bigList.size();i++) {//从大集合中的数据进行筛选
int num=bigList.get (i);
if(num%2==0) {
samllList.add(num);//筛选的结果放在samllList 然后返回结果
}
}
return samllList;
}
}
result:
偶数个数9
8 14 66 88 74 34 24 32 24(随机)