Arraylist集合存储基本数据类型以及集合练习

Arraylist集合存储基本数据类型

因为在集合中只能添加引用类型所以要添加基本数据类型就需要基本类型的包装类。

基本类型 包装类
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

 

 

 

 

 

 

 

 

 

复制代码
public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(123);
        list.add(456);
        list.add(789);
        System.out.println(list);
        System.out.println(list.get(1));
        System.out.println(list.remove(2));
        System.out.println(list.size());
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
复制代码

 

 

 

练习

存储随机数字

生成6个1~33之间的随机整数,添加到集合,并遍历集合。

复制代码
public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        Random ra = new Random();
        for (int i = 0; i < 6; i++) {
            int num = ra.nextInt(33) + 1;
            list.add(num);
        }
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
复制代码

 

存储自定义对象

自定义4个学生对象,添加到集合并遍历

复制代码
public class Student {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
复制代码
复制代码
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        Student student = new Student("张三", 15);
        Student student1 = new Student("李四", 28);
        Student student2 = new Student("王五", 46);
        Student student3 = new Student("赵六", 13);
        list.add(student);
        list.add(student1);
        list.add(student2);
        list.add(student3);
        for (int i = 0; i < list.size(); i++) {
            Student stu = list.get(i);
            System.out.println("姓名:"+stu.getName()+",年龄:"+stu.getAge());
        }
    }
复制代码

运行结果:

 

 

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