Reputation: 4239
In my problem, I created an object HashMapOfArrayList
. It has an instance method named transformation
, which essentially remove and add edges.
Problem lies in my Testing Class. I want to create a clone of the original Object (i.e. the graph I have when I load the text file) at each iteration. I do not know how to do this. And I think reading in the file again in each iteration, which is what I have now, is really inefficient. How should I create a clone in this situation ?
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();
}
}
}
}
Upvotes: 0
Views: 539
Reputation: 5937
You need a new constructor that takes your HashMapOfArrayList as an argument, and then all you need to do is clone the Integers in the 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);
}
}
Then, you can replace your original read with the cloning constructor and transform it.
for(int i = 0; i < 1000; i++){
HashMapOfArrayList clone = new HashMapOfArrayList(graph);
clone.transformation();
}
Upvotes: 1