Copy a Map Object in Java
Tried to follow the same way as in <How do I copy an object in Java?>.
But it does not work with Map object in the following codes. I want to copy the original map data to currMap. The current outputs are -
0 1 2 3 null null null
I want it to be - 0 1 2 3 0 2 3
What are missing here?
Thanks
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
class mapCopy{
private Map<Character, Queue<Integer>> map;
mapCopy(Map<Character, Queue<Integer>> map){
this.map=map;
}
mapCopy(mapCopy mapcopy){
this.map=mapcopy.map;
}
Map<Character, Queue<Integer>> getMap(){
return this.map;
}
}
public class Test {
static Map<Character, Queue<Integer>> BuildMap(){
String toMatch="able";
Map<Character, Queue<Integer>> map = new HashMap<>();
int i=0;
for(var c:toMatch.toCharArray()) {
Queue<Integer> q = map.get(c);
if(q==null)
q=new ArrayDeque<Integer>();
q.add(i);
map.put(c, q);
i++;
}
return map;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Character, Queue<Integer>> map = BuildMap();
List<String> dic = Arrays.asList("able", "ale");
for(var d:dic) {
var copy1 = new mapCopy(map);
var copy2 = new mapCopy(copy1);
var currMap = copy2.getMap();
for(var c:d.toCharArray()) {
System.out.println(currMap.get(c).poll());
}
}
}
}
from Recent Questions - Stack Overflow https://ift.tt/2Md23m2
https://ift.tt/eA8V8J
Comments
Post a Comment