Reputation: 1
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?
Upvotes: -2
Views: 52
Reputation: 1
Try This:
public static String sensitiveWordFilter(String sentence, HashMap<String, Object> map) throws Exception {
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 = (HashMap<String, Object>)map.get(key);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(tempMap);
oos.flush();
oos.close();
bos.close();
byte[] byteData = bos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
HashMap<String, Object> clonedMap = (HashMap<String, Object>) new ObjectInputStream(bais).readObject();
Map<String, Object> newMap = new HashMap<>();
newMap.put(key, clonedMap);
futureMap = (HashMap<String, Object>)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;
}
Upvotes: -1