public class Student { private int id; private String name; private String sex; public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class RSStudent { private String name; private String sex; public RSStudent() { } public RSStudent(Student stu) { //构造赋值 this.setName(stu.getName()); this.setSex(stu.getSex()); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
public static void fun() { // 创建多个对象放进stuList集合中 List<Student> stuList = new ArrayList<Student>(); for (int i = 0; i < 4; i++) { Student stu = new Student(); stu.setId(1 + i); stu.setName("张三" + i); stu.setSex(i%2==0?"男":"女"); stuList.add(stu); } // 把stuList集合中的对象放到rsList集合中(每次遍历都会把创建rs对象,并给其成员赋值,然后把赋完值之后rs对象添加到rsList集合中) List<RSStudent> rsList = new ArrayList<RSStudent>(); for (Student student : stuList) { // 遍历stuList集合中的student对象 RSStudent rsObj = new RSStudent(student);// 创建对象,把遍历出来的每个student对象传递到构造方法中 rsList.add(rsObj); } //遍历rsList集合 for (RSStudent rsStudent : rsList) { System.out.println(rsStudent.getName()+"---"+rsStudent.getSex()); } }