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()); } }
运行结果:


浙公网安备 33010602011771号