我正在使用Java 1.7
public static void main(String[] args) {
HashMap<Integer, String> testMap = new HashMap<Integer, String>();
testMap.put(1, "a");
String testString = testMap.get(1);
System.out.println("Before remove = " + testString);
testMap.remove(1);
System.out.println("After Remove " + testString);
}
输出结果为:
Before remove = a After Remove a
任何人都可以解释一下吗?
答案 0 :(得分:0)
正如评论中已提到的那样,您将再次打印testString
的存储值。
如果您想查看testString
中的更新值,则必须指定它
再次。像:
HashMap<Integer, String> testMap = new HashMap<Integer, String>();
testMap.put(1, "a");
String testString = testMap.get(1);
System.out.println("Before remove = " + testString);
testMap.remove(1);
testString = testMap.get(1);
System.out.println("After Remove " + testString);
现在输出将是:
Before remove = a
After Remove null
答案 1 :(得分:0)
从集合中删除元素不会更改引用对象的值 它仅更改地图内容:
String content = "test";
testMap.add(1, content);
testMap.remove(1);
System.out.println("After Remove " + testMap.get(1)); // "null" is printed
System.out.println("content"= + content) // content has not changed. So "test" is printed