ArrayList练习三_按指定格式遍历集合字符串与ArrayList练习四_筛选集合中的随机数
ArrayList练习三_按指定格式遍历集合字符串
对象添加到集合
自定义4个学生对象,添加到集合,并遍历
定义以指定格式打印集合的方法(ArrayList类型作为参数),使用{}扩起集合,使用@分隔每个元素。格式参照{元素@元素@元素}。 System.out.printLn(List); [10,20,30] printArrayList(list); {10@2e@30} */ public class Test02ArrayList { public static void main(String[] args) { //创建集合对象 ArrayList<Student> list = new ArrayList<Student>(); //创建学生对象 Student s1 = new Student("赵丽颖",18); Student s2 = new Student("唐嫣",20); Student s3 = new Student("景甜",25); Student s4 = new Student("柳岩",19); //把学生对象作为元素添加到集合中 list.add(s1); list.add(s2); list.add(s3); list.add(s4); //遍历集合 for(int x = 0; x < list.size(); x++) { Student s = list.get(x); System.out.println(s.getName()+"‐‐‐"+s.getAge()); } } }
获取集合方法
ArrayList练习四_筛选集合中的随机数
package demox.demopro; /* 题目: 用一个大集合存入20个随机数字,然后筛选其中的偶数元素,放到小集合当中。要求使用自定义的方法来实现筛选。 分析; 1.需要创建一个大集合,用来存储int数字: <Integer>2.随机数字就用Random nextInt 3,循环20次,把随机数字放入大集合:for循环、add方法 4、定义一个方法,用来进行筛选。 筛选:根据大集合,筛选符合要求的元素,得到小集合。三要素 返回值类型:ArrayList小集合(里面元素个数不确定)方法名称: getSmaLLList 参数列表:ArrayList大集合(装着20个随机数字) 5.判断(if)是偶数:num% 2 == 0 6.如果是偶数,就放到小集合当中,否则不放。 */ import java.util.ArrayList; import java.util.Random; public class Test04ArrayList { public static void main(String[] args) { // 创建Random 对象 Random random = new Random(); // 创建ArrayList 对象 ArrayList<Integer> list = new ArrayList<>(); // 添加随机数到集合 for (int i = 0; i < 20; i++) { int r = random.nextInt(1000) + 1; list.add(r); } // 调用偶数集合的方法 ArrayList<Integer> arrayList = getArrayList(list); System.out.println(arrayList); } public static ArrayList<Integer> getArrayList(ArrayList<Integer> list) { // 创建小集合,来保存偶数 ArrayList<Integer> smallList = new ArrayList<>(); // 遍历list for (int i = 0; i < list.size(); i++) { // 获取元素 Integer num = list.get(i); // 判断为偶数,添加到小集合中 if (num % 2 == 0){ smallList.add(num); } } // 返回小集合 return smallList; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)