// this is the hashCode method of Set
public int hashCode() {
int h = 0;
Iterator<E> i = iterator();
while (i.hasNext()) {
E obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}
//this is the hashCode method of List
public int hashCode() {
int hashCode = 1;
for (E e : this)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
return hashCode;
}
爲什麼java使用這兩種不同的方法?有什麼與Set和List的特性有關嗎? 爲什麼它使用31而不是其他數字? 謝謝!爲什麼Java實現Set和ArrayList的不同hashcode方法?
我回答了關於List vs Set的部分,因爲我在SO上找不到任何其他問題。但約31的位已經回答了:如果您搜索爲什麼散列函數使用素數,請參閱http://stackoverflow.com/questions/299304以及其他答案。 – yshavit