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