首页 > 其他 > 详细

Collections

时间:2021-09-06 02:51:54      阅读:13      评论:0      收藏:0      [点我收藏+]

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 + ‘\‘‘ +
                ‘}‘;
    }
}

 

Collections

原文:https://www.cnblogs.com/liuyang-520/p/15225819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!