Am 26.02.2010 12:52, schrieb Dmitry Nadezhin:
I found two alternatives in the link
http://mail.openjdk.java.net/pipermail/coin-dev/2009-December/002618.html
The first alternative
int equalByHashThreshold = 2;

public boolean equals(Object anObject) {
   if (this == anObject) {
     return true;
   }
   if (anObject instanceof String) {

     String anotherString = (String)anObject;
     int n = count;
     if (n == anotherString.count&&
         (equalByHashThreshold == 0 || --equalByHashThreshold == 0)&&
         (anotherString.equalByHashThreshold == 0 || 
--anotherString.equalByHashThreshold == 0)&&


         hash() == anotherString.hash()) {
[snipped]
     }
   }
   return false;
}
will say that
"A".equals("A") == false
because body of if statement will not be executed

I don't understand your problem.
1. String literals are always interned, so "A" is always identical to "A". Therefore the body of the 1st if will return true. 2. If the strings are not identical, body of 2nd if will be executed, if anObject is instance of String.


The second alternative
public int hashCode() {
   int h = hash;
   if (h == 0 || --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;
}
will return sequentially

"A".hashCode() == 65
"A".hashCode() == 64
"A".hashCode() == 64
. . .

You are right. Good catch.

So better:

public int hashCode() {
  int h = hash;
  if (h == 0) {
    int len = count;
    if (len>  0) {
      char[] val = value;
      for (int i = 0, off = offset; i<  len; i++)
        h = 31*h + val[off++];
      hash = h;
    }
  } else if (h == 1) {
    hash = 0;
    return hashCode();
  }
  return h;
}


- Ulf


Reply via email to