gpt4 book ai didi

java - LinkedList 和 TreeMap : compareTo or equals?

转载 作者:行者123 更新时间:2023-11-29 04:12:17 26 4
gpt4 key购买 nike

我需要澄清有关 TreeMap 和 LinkedList 的使用。这两个结构是使用 compareTo 还是 equals?

特别是,TreeMap 保持键中的顺序,我想使用为键定义的类的 compareTo 方法。但是,在使用get的时候,他们是使用compareTo还是equals来查看你传递的key是否被包含?

我对LinkedList里面的contains和getIndex也有同样的疑问。

最佳答案

TreeMap使用 compareTo , 和 the documentation如果 compareTo 会警告您问题与equals不一致(即 a.compareTo(b) == 0 <=> a.equals(b) 应该是真的)。​​

Note that the ordering maintained by a tree map ... must be consistent with equals if this sorted map is to correctly implement the Map interface.

LinkedList使用 equals .


为什么TreeMap的原因必须使用与 equals 一致的顺序是Map的契约(Contract)吗根据 equals 定义行为.例如, containsKey 定义为:

returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))

假设您这样定义一个类:

class Bad implements Comparable<Bad> {
@Override public int compareTo(Bad other) { return 0; }
}

如果你要写:

Bad b1 = new Bad();
Bad b2 = new Bad();

然后:

Map<Bad, String> hm = new HashMap<>();
hm.put(b1, "");
System.out.println(hm.containsKey(b2)); // false

鉴于

Map<Bad, String> tm = new TreeMap<>();
tm.put(b1, "");
System.out.println(tm.containsKey(b2)); // true

虽然

System.out.println(tm.keySet().stream().anyMatch(k -> k.equals(b2))); // false

因此,TreeMap违约Map ,因为 Bad不执行Comparableequals 一致.

关于java - LinkedList 和 TreeMap : compareTo or equals?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54418101/

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