Java浅Copy的一些事

栏目: Java · 发布时间: 5年前

内容简介:最近发现了一个现象:用调研了于是乎就换了一个种方式来写:

最近发现了一个现象:用 BeanUtils.copyProperties(Object source, Object target) 时, 如果source和target中有 List 对象,然后修改了source的 List 对象中的元素,发现target的 List 对象也会跟着变化。

调研了 BeanUtils.copyProperties(Object source, Object target) 源码,发现是通过 method.invoke 方法来实现属性的copy的,所以对象的属性复制都是浅Copy。

于是乎就换了一个种方式来写:

List<A> source = new ArrayList<>();
source.add(new A());
List<A> copy = new ArrayList<>(source);
复制代码

发现居然还是不行!

觉得很奇怪,然后看了 ArrayList 的构造方法,

public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
复制代码

elementData = c.toArray() 这段代码还是浅Copy。

思考了一会,难道只能通过遍历元素,然后添加元素的方式来解决吗?抱着疑问去Google了下,发现该函数 Collections.copy 解决了问题,进入其源码发现是在遍历元素然后再添加。。。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Design and Analysis of Distributed Algorithms (Wiley Series on P

Design and Analysis of Distributed Algorithms (Wiley Series on P

Nicola Santoro / Wiley-Interscience / 2006-10-27 / USD 140.95

This text is based on a simple and fully reactive computational model that allows for intuitive comprehension and logical designs. The principles and techniques presented can be applied to any distrib......一起来看看 《Design and Analysis of Distributed Algorithms (Wiley Series on P》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具