import java.util.HashMap;
public class test {
public static void main(String[] args) {
HashMap<String, Object> map1 = new HashMap<>();
HashMap<String, Object> map2 = new HashMap<>();
HashMap<String, Object> map3 = new HashMap<>();
map3.put("isEnd", 2);
map2.put("x", map3);
map1.put("y", map2);
String sentence = "xyxy";
sensitiveWordFilter(sentence, map1);
}
public static String sensitiveWordFilter(String sentence, HashMap<String, Object> map){
System.out.println("original map: " + map);
HashMap<String, Object> futureMap = new HashMap<>();
for(int i = 0; i < sentence.length(); i++){
char char_ = sentence.charAt(i);
for (String key : map.keySet()){
if (String.valueOf(char_).equals(key)){
HashMap<String, Object> tempMap = new HashMap<>();
tempMap.putAll((HashMap<String, Object>) map.get(key));
HashMap<String, Object> newMap = new HashMap<>();
newMap.put(key, tempMap);
futureMap = newMap;
}
}
if (futureMap.get(String.valueOf(char_)) != null){
futureMap = (HashMap<String, Object>) futureMap.get(String.valueOf(char_));
if (futureMap.get("isEnd") != null){
System.out.println("---------------" + map + "--------------------");
futureMap.remove("isEnd");
System.out.println("---------------" + map + "--------------------");
}
}
}
return sentence;
}
}
This is the code that can be executed directly. You can clearly see that the value of map changes with the change of futureMap. It can be said that the deep copy is invalid. What's wrong?