# 集合中的hashCode和equals方法

47. 全排列 II

``````輸入: [1,1,2]

[
[1,1,2],
[1,2,1],
[2,1,1]
]``````

————————————————————————————————————————————————————

set添加元素時，第一比較hashCode，第二比較equals方法

A.equals(B) 是false

1 首先查看ArrayList的hashCode()和equals方法，看下源碼：

``````   public int hashCode() {
int hashCode = 1;
for (E e : this)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
return hashCode;
}
``````

``````   public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;

ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}
``````

equals方法也是和存儲的數據類型的equals方法相關的。

`````` public static int hashCode(int value) {
return value;
}

public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}``````

（但是注意地址不一定相等，只有[-128,127]會使用緩存）

``````class Solution {
HashSet<LinkedList<Integer>> set = new HashSet<>();
public List<List<Integer>> permuteUnique(int[] nums) {
boolean[] visited = new boolean[nums.length];
permute(nums,0,visited);
return new ArrayList(set);

}
public void permute(int[] nums,int k,boolean[] visited) {
if(k==nums.length) {
return;
}
for(int i =0;i<nums.length;i++) {
if(!visited[i]) {
visited[i] = true;
permute(nums,k+1,visited);
visited[i] = false;
temp.removeLast();
}
}
}
}
``````

``````輸入：s = "abc"

`````` public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;

for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}``````
``````   public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}``````