繁体   English   中英

Set中contains()和remove()的行为,该行为由entrySet()返回

[英]Behavior of contains() and remove() on Set which is returned by entrySet()

我有以下代码。 为什么包含并删除退货错误?

    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]

entrySet()返回一Set Map.Entry实例。 因此您的查找失败,因为Map.Entry<Integer, String>类型的对象永远不能等于Integer实例。

您应该注意通用签名,即

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]

如果要处理而不是条目,则必须使用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]

为了完整起见,请注意Map的第三个集合视图values() 根据实际操作,选择正确的视图可以大大简化操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM