gpt4 book ai didi

java - 由entrySet()返回的Set上的contains()和remove()的行为

转载 作者:行者123 更新时间:2023-12-02 02:00:19 24 4
gpt4 key购买 nike

我有以下代码。为什么包含和删除返回 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]

最佳答案

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的第三个 Collection View ,values() 。根据实际操作,选择正确的 View 可以极大地简化您的操作。

关于java - 由entrySet()返回的Set上的contains()和remove()的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51682692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com