Java:如何克隆 ArrayList 的 HashMap ?

标签 java clone

在我的问题中,我创建了一个对象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 中的整数。

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();
}

关于Java:如何克隆 ArrayList 的 HashMap ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27409866/

相关文章:

使用不同的用户名/帐户进行 git 克隆

java - Spring : Bean class is not recognised by the spring and throwing ClassNotFoundException

java - 从列表中采样和删除随机元素

java - Selenium 驱动程序 - 在列表中选择所需的 li 项

java - 我如何从 swing 应用程序调用 GWT 方法

version-control - 使用 Fossil 克隆存储库?

java - 使用java处理多个csv行

javascript - 如何将 div 克隆放在原始 div 的正下方?

jquery克隆div并将其附加到特定div之后

java - 这个 clone() 有什么问题?