这是hashCode()的源代码,一看便知 /** The value is used for character storage. */ private final char value[]; /** The offset is the first index of the storage that is used. */ private final int offset; /** The count is the number of characters in the String. */ private final int count; /** Cache the hash code for the string */ private int hash; // Default to 0 public int hashCode() { int h = hash; if (h == 0) { int off = offset; char val[] = value; int len = count; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; }
if a.equals(b)==true 那么hashcode也相同,如果hashcode相同,未必 equals成立
if a.equals(b)==true 那么hashcode也相同,如果hashcode相同,未必 equals成立这个是理论上应该这样,实际操作时,只要程序员重写EQUALS方法的时候没有重写HASHCODE,那就可能发生EQUALS方法为TRUE,hashcode不相同的情况。不是说这样不可以,也可以,但是HASHCODE已经失去了作用。
/** The value is used for character storage. */
private final char value[]; /** The offset is the first index of the storage that is used. */
private final int offset; /** The count is the number of characters in the String. */
private final int count; /** Cache the hash code for the string */
private int hash; // Default to 0
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count; for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
-------
不是“最好”而是“必须”!