### HashSet的contains()函数先调用hashCode()比较散列值，再调用equals()函数

HashSet的contains()函数调用的是HashMapcontainsKey()函数， 后者比较元素是先调用hashCode()比较两者的散列值，再调用equals()函数进行比较。

public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
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;
}


### 错误范例

public boolean containsAllPoints(int[][] points, int[][] testCollection) {
Set<Point> pointsSet = new HashSet<>();
for (int[] point : points) {
}
Point expected = new Point(); //为了节省空间，只创建一个点对象
for (int[] point : testCollection) {
expected.x = point[0]; //每次都更新这个点对象的数据
expected.y = point[1];
if (!pointsSet.contains(expected)) {
System.out.println("点：" + expected + "没找到！");
}
System.out.println("点：" + expected + "找到了！");
}
}


Point类重写了equals()函数，它同时比较x轴和y轴坐标。

private class Point {
private int x; //点的x轴坐标
private int y; //点的y轴坐标
private Point() {
x = 0;
y = 0;
}
private Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) { //equals()函数同时比较点的x轴和y轴坐标
Point anotherPoint = (Point)obj;
return (anotherPoint.x == x) && (anotherPoint.y == y);
}
private int hash = 0;
@Override
public int hashCode() {
if (hash == 0) { //惰性更新是罪魁祸首
hash = x * 31 + y;
}
return hash;
}
}