Use ArrayList como
tema de tipo de valor de retorno : use una colección grande para almacenar 20 números aleatorios, luego filtre los elementos pares entre ellos y colóquelos en una colección pequeña.
Use un método personalizado para lograr el
análisis:
1. Necesita crear una colección grande, use Para almacenar números int, <Integer>
2. Los números aleatorios usan Random nextInt ()
3. Bucle 20 veces, pulse números aleatorios en una gran colección: para bucle, agregue el método
4. Defina un método para el
cribado: la base es grande Colección, filtre los elementos que cumplan los requisitos, obtenga una pequeña colección
Tres elementos:
tipo de valor de retorno: colección pequeña ArrayList (el número de elementos es incierto)
Nombre del método:
lista de parámetros getSmallList : colección grande ArrayList (con 20 elementos aleatorios)
5. El juicio (si) es una función par: num% 2 == 0;
6. Si es par, póngalo en un conjunto pequeño, de lo contrario no lo ponga
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(随机)