ArrayList练习-存储随机数和存储自定义对象

ArrayList练习-存储随机数

生成6个1~33之间的随机整数,添加到集合,并遍历集合。
思路:
1.需要存储6个数字,创建一个集合,<Integer>

2.   产生随机数,需要用到Random

3.用循环6次,来产生6个随机数字:for循环

4.循环内调用r.nextInt(int n),参数是33,0~32,整体+1才是1~33

5.把数字添加到集合中:add

6.遍历集合:for、size、 get

复制代码
   ArrayList<Integer> list2 = new ArrayList<Integer>();
        Random r = new Random() ;
        for (int i = 0; i < 6; i++) {
            int num1 = r.nextInt( 33) + 1;
            list2.add(num1) ;
        }
        //遍历集合
        for (int i = 0; i < list.size(); i++) {
            System.out.println( list.get(i));
        }
复制代码

 

ArrayList练习-存储自定义对象

题目:
自定义4个学生对象,添加到集合,并遍历。
思路;
1.自定义Student学生类,四个部分。

2.创建—个集合,用来存储学生对象。泛型:<Student>

3.根据类,创建4个学生对象。

4.将4个学生对象添加到集合中: add5.遍历集合:for、 size、get

复制代码
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<Student>();
        
        
        Student one = new Student(  "洪七公",  20);
        Student two = new Student( "欧阳锋",  21);
        Student three = new Student( "黄药师",  22);
        Student four = new Student(  "段智兴", 23);
        
        list.add(one);
        list.add(two);
        list.add(three);
        list.add(four);
        
        //遍历集合
        for (int i = 0; i < list.size(); i++) {
            Student stu = list.get(i);
            System.out.println("姓名:" + stu.getName() + ",年龄" + stu.getAge());
    }
复制代码

 

posted @   漁夫  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示