簡體   English   中英

將值重新分配給新對象,進行深度克隆,更好的解決方案?

[英]Re-assign values to new object, deep clone, better solution?

我有一個對象,其中包含多個字段(int,String等),還包含HashMap和ArrayList。 該對象保存用於以后構建數據庫查詢的參數,但是有時需要重復使用所有完全相同的參數進行附加查詢,但ArrayList中的不同項除外。

我注意到,當我更改數組列表中的內容時,它始終會更改原始對象。 我已經想出了如何通過覆蓋clone()方法制作淺表副本,但是數組列表始終保持為對象的任何副本所共享。 在深入研究類似內容之前,我想我需要關於這是否是最佳途徑的建議。

這是我需要找到一種復制方法的對象的示例。

public class QueryParameters implements Cloneable {

    protected HashMap<String,String> foundArgs = new HashMap<String,String>();
    protected ArrayList<ActionType> action_types = new ArrayList<ActionType>();

    protected String lookup_type = "lookup";
    protected Location loc;
    protected Vector player_location;
    protected int id = 0;
    protected int radius;
    protected boolean allow_no_radius = false;
    protected String player;
    protected String world;
    protected String time;
    protected String entity;
    protected String block;
    // ... lots of getters/setters
}

我總是可以創建一個新實例並使用getter / setter來傳輸數據,但這對我來說太冗長了-我必須復制大約15個字段,如果要添加新字段,我需要記住在這里添加它們。

對我來說,獲取新實例/克隆的最佳方法是什么,以便對action_types更改不會影響原始對象

如果“克隆自己的類”,則無需使用getter和setter。 像這樣的構造函數?

private QueryParameter(QueryParameter other)
{
    foundArgs = new HashMap<String, String>(other.foundArgs);
    action_types = new ArrayList<ActionType>(other.action_types);
    // etc
}

// As a static method, or
public static QueryParameter copyOf(QueryParameter other)
{
    return new QueryParameter(other);
}

// as an instance method
public QueryParameter copy()
{
    return new QueryParameter(this);
}

這是許多解決方案中的一種...

我建議編寫一個克隆方法,該方法使用super.clone()復制大多數字段,然后替換克隆中的ArrayList。 像這樣:

import java.util.ArrayList;

public class QueryParameters implements Cloneable {
  @Override
  public String toString() {
    return "QueryParameters [action_types=" + action_types + ", otherData="
        + otherData + "]";
  }

  protected ArrayList<String> action_types = new ArrayList<String>();
  protected String otherData;

  @Override
  public QueryParameters clone() throws CloneNotSupportedException {
    QueryParameters cloned = (QueryParameters) super.clone();
    cloned.action_types = new ArrayList<String>(action_types);
    return cloned;
  }

  public static void main(String[] args) throws CloneNotSupportedException {
    QueryParameters test = new QueryParameters();
    test.otherData = "a field";
    test.action_types.add("xyzzy");
    test.action_types.add("abcde");
    System.out.println("Original: " + test);
    QueryParameters clone = test.clone();
    clone.action_types.add("A new action type");
    System.out.println("Modified clone: " + clone);
    System.out.println("Original after clone modification: " + test);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM