定义一个学生类,添加到集合,并遍历
1 import java.util.ArrayList; 2 3 public class Demo02ArrayList { 4 public static void main(String[] args) { 5 ArrayList<Student> stu = new ArrayList<>(); 6 Student student1 = new Student("小明", 27, "1231231231","男"); 7 Student student2 = new Student("小方", 22, "1232341231","男"); 8 Student student3 = new Student("小小", 23, "1231123121","男"); 9 Student student4 = new Student("小齐", 29, "1234231231","男"); 10 stu.add(student1); 11 stu.add(student2); 12 stu.add(student3); 13 stu.add(student4); 14 for (int i = 0; i < stu.size(); i++) { 15 Student stu1 = stu.get(i); 16 System.out.println("姓名:"+stu1.getName()+" "+"年龄:"+stu1.getAge()+" "+"学号:"+stu1.getNo()+" "+"性别:"+stu1.getSex() ); 17 } 18 } 19 }
学生类
1 public class Student { 2 private String name; 3 private int age; 4 private String no; 5 private String sex; 6 7 public Student() { 8 } 9 10 public Student(String name, int age, String no, String sex) { 11 this.name = name; 12 this.age = age; 13 this.no = no; 14 this.sex = sex; 15 } 16 17 public String getName() { 18 return name; 19 } 20 21 public void setName(String name) { 22 this.name = name; 23 } 24 25 public int getAge() { 26 return age; 27 } 28 29 public void setAge(int age) { 30 this.age = age; 31 } 32 33 public String getNo() { 34 return no; 35 } 36 37 public void setNo(String no) { 38 this.no = no; 39 } 40 41 public String getSex() { 42 return sex; 43 } 44 45 public void setSex(String sex) { 46 this.sex = sex; 47 } 48 }
浙公网安备 33010602011771号