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()); } }
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix