深层复制字符串数组

时间:2013-12-10 21:05:41

标签: deep-copy cloneable

我需要演示一个代码,它为JAVA中的字符串数组实现深层复制。以下是我开发的代码。任何人都可以确认它是否正确?

    public class Paper implements Cloneable{

private String Type ; 
private String[] Text ; 

//Default constructor to initialize variables.
public Paper()
{ 
        this.Type="" ; 
    this.Text = new String[0]  ;  
}

//Necessary constructor.
public Paper(String Type, String[] Text)
{
this.Type= Type;
//Deep copy 
this.Text = new String[Text.length] ; 
this.Text = Text.clone() ;
//Flat Copy
this.Text = Text ; 
}

//Here we implements the interface "Cloneable" to make deep copy when we want to 
//extend an array of Paper objects.
public Object clone()
{
    try
    {
        Paper cloned = (Paper) super.clone();
        cloned.Text = (String[])Text.clone();
        return cloned;
    }
    catch(CloneNotSupportedException e)
    {
        return null;
    }
}

0 个答案:

没有答案