[英]Behavior of contains() and remove() on Set which is returned by entrySet()
I have following code. 我有以下代码。 Why contains & remove returns false? 为什么包含并删除退货错误?
Map<Integer, String> p = new TreeMap();
p.put(1, "w");
p.put(2, "x");
p.put(3, "y");
p.put(4, "z");
System.out.println(p);// {1=w, 2=x, 3=y, 4=z}
Set s = p.entrySet();
System.out.println(s);// [1=w, 2=x, 3=y, 4=z]
System.out.println(s.contains(1));//false
System.out.println(s.remove(1));//false
System.out.println(p);// {1=w, 2=x, 3=y, 4=z}
System.out.println(s);// [1=w, 2=x, 3=y, 4=z]
The entrySet()
returns a Set
of Map.Entry
instances. entrySet()
返回一Set
Map.Entry
实例。 So your lookup fails, as objects of type Map.Entry<Integer, String>
can never be equal to instances of Integer
. 因此您的查找失败,因为Map.Entry<Integer, String>
类型的对象永远不能等于Integer
实例。
You should pay attention to the generic signatures, ie 您应该注意通用签名,即
Map<Integer, String> p = new TreeMap<>();
p.put(1, "w");
p.put(2, "x");
p.put(3, "y");
p.put(4, "z");
System.out.println(p);// {1=w, 2=x, 3=y, 4=z}
Set<Map.Entry<Integer, String>> s = p.entrySet();
System.out.println(s);// [1=w, 2=x, 3=y, 4=z]
Map.Entry<Integer, String> entry = new AbstractMap.SimpleEntry<>(1, "foo");
System.out.println(s.contains(entry)); // false (not containing {1=foo})
entry.setValue("w");
System.out.println(s.contains(entry)); // true (containing {1=w})
System.out.println(s.remove(entry));// true
System.out.println(p);// {2=x, 3=y, 4=z}
System.out.println(s);// [2=x, 3=y, 4=z]
If you want to process keys instead of entries, you have to use keySet()
instead: 如果要处理键而不是条目,则必须使用keySet()
:
Map<Integer, String> p = new TreeMap<>();
p.put(1, "w");
p.put(2, "x");
p.put(3, "y");
p.put(4, "z");
System.out.println(p);// {1=w, 2=x, 3=y, 4=z}
Set<Integer> s = p.keySet();
System.out.println(s);// [1, 2, 3, 4]
System.out.println(s.contains(1)); // true
System.out.println(s.remove(1));// true
System.out.println(p);// {2=x, 3=y, 4=z}
System.out.println(s);// [2, 3, 4]
For completeness, note Map
's 3rd collection view, the values()
. 为了完整起见,请注意Map
的第三个集合视图values()
。 Depending on the actual operation, choosing the right view can simplify your operation dramatically. 根据实际操作,选择正确的视图可以大大简化操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.