如果没有测试Java方法是否深层复制,通用规则是什么?

时间:2011-07-30 08:26:27

标签: java

以下是从List.addAll文档中获取的一个(典型?)示例,它似乎没有说明目标列表的添加是否是深层副本。除了测试之外,快速解析文档或一般理解的一般方法是什么,允许确定标准Java类和方法是否深层复制? Oracle writeup on List.addAll

addAll

boolean addAll(Collection<? extends E> c)

    Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list, and it's nonempty.)

    Specified by:
        addAll in interface Collection<E>

    Parameters:
        c - collection containing elements to be added to this list 
    Returns:
        true if this list changed as a result of the call 
    Throws:
        UnsupportedOperationException - if the addAll operation is not supported by this list 
        ClassCastException - if the class of an element of the specified collection prevents it from being added to this list 
        NullPointerException - if the specified collection contains one or more null elements and this list does not permit null elements, or if the specified collection is null 
        IllegalArgumentException - if some property of an element of the specified collection prevents it from being added to this list
    See Also:
        add(Object)

2 个答案:

答案 0 :(得分:3)

除非某些指定需要深层复制,否则我总是认为它没有。很难拍摄深拷贝,特别是因为它依赖于支持克隆的对象本身。

答案 1 :(得分:2)

Java标准API上的没有方法可以执行深层复制。深层拷贝通常只通过序列化隐式发生(可能也是克隆,但我从未见过这个),并且一些框架/库可以通过实用方法明确地提供它,但它是一个罕见的例外,甚至不可能为任意{ {1}}秒。