簡體   English   中英

Java:如何克隆ArrayList的HashMap?

[英]Java: How can I make a clone of a HashMap of ArrayList ?

在我的問題中,我創建了一個對象HashMapOfArrayList 它具有一個名為transformation的實例方法,該方法實質上刪除和添加了邊緣。

問題出在我的測試班上。 我想在每次迭代時創建原始對象(即加載文本文件時的圖形)的副本。 我不知道該怎么做。 而且我認為在每次迭代中再次讀取文件(這是我現在所擁有的)的效率真的很低。 在這種情況下,我應該如何創建克隆?

class HashMapOfArrayList{
     HashMap<Integer, ArrayList<Integer>> my_graph;

     // constructor
     public HashMapOfArrayList(){
                my_graph = new HashMap<Integer, ArrayList<Integer>>();
     }
      .......
}

class Testing{
    public static void main(String[] args) throws IOException{
        HashMapOfArrayList graph = new HashMapOfArrayList();
        graph.read_file_and_populate("file.txt");
        for(int i = 0; i < 1000; i++){ 
// Need a way to clone the object instead of reading in the file many times.
                HashMapOfArrayList graph = new HashMapOfArrayList();
                graph.read_file_and_populate("file.txt");
                graph.transformation();
                }
            }
        }
    }

您需要一個新的構造函數,該構造函數將HashMapOfArrayList用作參數,然后所需要做的就是在ArrayList中克隆Integers。

public HashMapOfArrayList(HashMapOfArrayList source) {
    HashMap<Integer, ArrayList<Integer>> graph = source.getGraph(); // get the source graph

    my_graph = new HashMap<Integer, ArrayList<Integer>>(); //define our graph 
    for(Map.Entry<Integer, ArrayList<Integer>> entry : graph.entrySet()) {
        //iterate through the graph
        ArrayList<Integer> sourceList = entry.getValue();
        ArrayList<Integer> clonedList = new ArrayList<Integer>();
        clonedList.addAll(sourceList);
        //put value into new graph
        my_graph.put(entry.getKey(), clonedList);
    }
}

然后,您可以將原始讀取內容替換為克隆構造函數並進行轉換。

for(int i = 0; i < 1000; i++){ 
    HashMapOfArrayList clone = new HashMapOfArrayList(graph);
    clone.transformation();
}

暫無
暫無

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

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