Collections
1、Collections.copy(非深度拷贝,拷贝后对应位置上的元素都指向同一个地址)
package demo02; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * @description: demo03 * @author: liuyang * @create: 2021-09-04 9:09 */ public class Demo03 { @Test public void test1() { List<Student> fromList = new ArrayList<>(); fromList.add(new Student("小文", new Course("语文"))); fromList.add(new Student("小明", new Course("数学"))); fromList.add(new Student("小强", new Course("英语"))); List<Student> toList = Arrays.asList(new Student[fromList.size()]); Collections.copy(toList, fromList); // 非深度拷贝,拷贝后对应位置上的元素都指向同一个地址 fromList.get(0).setStudentName("liuyang"); fromList.get(0).getCourse().setCourseName("物理"); System.out.println(fromList); System.out.println(toList); } } class Student { private String studentName; private Course course; public Student(String studentName, Course course) { this.studentName = studentName; this.course = course; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } @Override public String toString() { return "Student{" + "studentName='" + studentName + '\'' + ", course=" + course + '}'; } } class Course { private String courseName; public Course(String courseName) { this.courseName = courseName; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } @Override public String toString() { return "Course{" + "courseName='" + courseName + '\'' + '}'; } }
相识是缘