1.ArrayList同样可以添加自定义的类
将学生类添加到ArrayList集合中,其中学生类包括学生姓名,年龄
自定义学生类
package demo1; public class Student { String name; int age; }
将学生类添加到ArrayList集合中
package demo1; import java.util.ArrayList; import java.util.Random; public class Demo1 { public static void main(String[] args) { ArrayList<Student> array = new ArrayList<Student>(); //定义ArrayList集合来盛放Student类 add(array); //添加数据到集合中 printArrayList(array); //打印集合数据 } //打印集合数据 public static void printArrayList(ArrayList<Student> array) { for (int i = 0; i < array.size(); i++) { Student s = array.get(i); System.out.println(s.name+" "+s.age); } } //添加数据到集合中 public static void add(ArrayList<Student> array) { Student s1 = new Student(); s1.name = "张三"; s1.age = 23; Student s2 = new Student(); s2.name = "李四"; s2.age= 24; array.add(s1); array.add(s2); } }
2.学生的随机点名器
先添加学生类
package demo1; import java.util.ArrayList; import java.util.Random; public class Demo1 { public static void main(String[] args) { ArrayList<Student> array = new ArrayList<Student>(); addStudent(array); printArrayList(array); randomStudent(array); } //生成随机数,选择对应的学生,打印姓名和年龄 public static void randomStudent(ArrayList<Student> array) { Random ran = new Random(); int index = ran.nextInt(array.size()); Student s = array.get(index); System.out.println("选择的学生是:"+s.name+" 年龄为:"+s.age); } //打印集合 public static void printArrayList(ArrayList<Student> array) { for (int i = 0; i < array.size(); i++) { Student s = array.get(i); System.out.println(s.name+" "+s.age); } } //向集合中添加Student数据 public static void addStudent(ArrayList<Student> array) { Student s1 = new Student(); s1.name = "张三"; s1.age = 23; Student s2 = new Student(); s2.name = "李四"; s2.age = 24; Student s3 = new Student(); s3.name = "王五"; s3.age = 25; Student s4 = new Student(); s4.name = "马六"; s4.age = 26; array.add(s1); array.add(s2); array.add(s3); array.add(s4); } }