Friday, September 30, 2005

Một sai lầm khi thiết kế class String???

Trong cuốn Java Programming Language 4th, method hashCode() của class Object được mô tả như sau:

public int hashCode()

Returns a hash code for this object. Each object has a hash code for use in hashtables. The default implementation returns a value that is usually different for different objects.

Thế nhưng khi thiết kế class String, người thiết kế lại cài đặt mã của method hashCode() như sau:

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;
}

Với mã của method hashCode() của class String được cài đặt như trên thì

String s1 = "OK";



String s2 = new String("OK");

tuy là 2 object khác nhau nhưng lại có hash code như nhau.

Đây có phải là một sai lầm (sai semantic)?

1 comment:

Unknown said...

http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode()

hashCode is used in a hashtables. Two objects that have the same value must have the same hash code.

So, it is probably a problem with the book if it didn't clear that out.