• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

TreeMap和HashMap的元素比较

2周前 (04-07) 10次浏览

写在前面的话

2021.04，准备面试和CCF CSP认证的我准备做一套CCF模拟题，然后就有了此篇博客(x

TreeSet compare和contains

错误代码

``````public static int score(int x, int y, Set<Point1912> set) {
if (set.contains(new Point1912(x + 1, y)) && set.contains(new Point1912(x - 1, y)) && set.contains(new Point1912(x, y + 1)) && set.contains(new Point1912(x, y - 1))) {
int sum = 0;
sum += (set.contains(new Point1912(x + 1, y + 1)) ? 1 : 0);
sum += (set.contains(new Point1912(x - 1, y + 1)) ? 1 : 0);
sum += (set.contains(new Point1912(x + 1, y - 1)) ? 1 : 0);
sum += (set.contains(new Point1912(x - 1, y - 1)) ? 1 : 0);
return sum;
} else {
return -1;
}
}
``````

``````class Point1912 {
int x = 0;
int y = 0;
int seq = 0;

public Point1912(int x, int y) {
this.x = x;
this.y = y;
}

public Point1912(int x, int y, int seq) {
this.x = x;
this.y = y;
this.seq = seq;
}

@Override
public boolean equals(Object obj) {
Point1912 p = (Point1912) obj;
return x == p.x && y == p.y;
}

@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
``````

TreeSet代码

``````TreeSet<Point1912> set1 = new TreeSet<>(((o1, o2) -> o1.seq - o2.seq));
``````

调试

查看源码

``````final Entry<K,V> getEntryUsingComparator(Object key) {
@SuppressWarnings("unchecked")
K k = (K) key;
Comparator<? super K> cpr = comparator;
if (cpr != null) {
Entry<K,V> p = root;
while (p != null) {
int cmp = cpr.compare(k, p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
}
return null;
}
``````

解决方案

``````final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
``````

总结

TreeMap中元素的比较采用的是Comparator，或者是元素实现的Comparable接口；
HashMap中元素的比较便是元素的equals方法。