标准API中是否有可以深度克隆列表的方法?

时间:2015-03-26 15:40:33

标签: java arraylist clone

在大约30天内,我将参加Java比赛。在比赛中,我们将使用Eclipse和Java 1.7 API交付计算机。我正在练习去年比赛的任务,我反复发现需要深度克隆一个列表。由于时间有限且唯一可用的Java 1.7 API,有没有办法做到这一点?

我已经看到了几个解决方案,包括

  • 实施Cloneable界面。
  • 导入Java深度克隆库
  • 将克隆构造函数实现到List所持有的任何对象的类,并迭代元素。

但是这些解决方案要么在竞赛中无法使用,要么耗费时间。现在,我需要深度克隆包含ArrayList s的ArrayList个对象。

有谁知道这是否可能?谢谢大家的帮助!

2 个答案:

答案 0 :(得分:2)

这完全取决于列表中的内容。所以,简短的回答是:不。

您可以尝试序列化整个List,但这要求List中的所有内容都可以序列化。您可以编写一个deepClone()方法,该方法对List中的所有内容调用clone()方法,但这取决于List中正确实现clone()方法的每个Object。

这是一个竞赛问题的全部原因是没有一个快速的“一刀切”解决方案。

答案 1 :(得分:0)

除了调用clone之外,您还可以将所有内容写入ByteArrayOutputStream并再次读取它。

看看这是否对您有所帮助:

  static public <T> T deepCopy(T oldObj) throws Exception {
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    try {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream( bos);
      oos.writeObject( oldObj);
      oos.flush();
      ByteArrayInputStream bin = new ByteArrayInputStream( bos.toByteArray());
      ois = new ObjectInputStream( bin);

      return (T) ois.readObject();
    } catch( Exception e) {
      e.printStackTrace();
      throw ( e);
    } finally {
      if( oos != null) {
        oos.close();
      }
      if( ois != null) {
        ois.close();
      }
    }
  }

用法e。 G:

public class Testing {

  public static void main(String[] args) throws Exception {

    List<Object> list = new ArrayList<>();
    list.add( "A");
    list.add( "B");
    list.add( 1);
    list.add( 2);
    list.add( new BigDecimal( 123.456839572935879238579238754938741321321321321593857));
    list.add( new MyParentObject( 12345, "abcdef", new MyChildObject( "child")));

    List clone = (List) Tools.deepCopy( list);

    for( Object obj: clone) {
      System.out.println( obj);
    }

    System.exit(0);
  }

  private static class MyParentObject implements Serializable {
    int a;
    String b;
    MyChildObject child;

    public MyParentObject(int a, String b, MyChildObject child) {
      super();
      this.a = a;
      this.b = b;
      this.child = child;
    }

    public String toString() {
      return a + ", " + b + ", " + child;
    }
  }

  private static class MyChildObject implements Serializable {
    String s;

    public MyChildObject( String s) {
      this.s = s;
    }

    public String toString() {
      return s;
    }
  }
}

输出:

A
B
1
2
123.456839572935876958581502549350261688232421875
12345, abcdef, child