Will Sun's implementation ever find ReusableKey if the value has been changed?

It would not surprise me if this simple case Sun doesn't find the entry, because they do something like hashing the hash that ReusableKey returns, or only allocating a prime number of buckets, e.g. you ask for a size of 16 and get 17, because 16 is not prime.

This doesn't actually seems like crazy behaviour, since it is probably rather common to have programmers that are not very good at creating well distributed hashing algorithms, and so having something built in to help is probably pretty good design.

   --Will

Paulex Yang wrote:

Pls. try the test case on HashMap below.

On RI, it print out:
null
null

On Harmony, it print out
null
value1

it is definitely bad practice to reuse a object as hash key by modify its hashcode, but I DID see some similar cases before, after all, you cannot force but only can *suggest* developers what to do.

So, what should we do?  Try to replicate RI's behavior?


public class HashMapTest {
public static void main(String[] args) {
 ReusableKey k = new ReusableKey();
 HashMap map = new HashMap();
 k.setKey(1);
 map.put(k, "value1");

 k.setKey(18);
 //both RI and Harmony get null here
 System.out.println(map.get(k));

 k.setKey(17);
 //RI get null
 //Harmony get "value1"
//the number of 17 is *magic* because the default length of HashMap is 16.
 System.out.println(map.get(k));
}
}

class ReusableKey{
private int key = 0;
public void setKey(int key){
 this.key = key;
}
public int hashCode(){
 return key;
}
public boolean equals(Object o){
 if(o == this){
  return true;
 }
 if(!(o instanceof ReusableKey)){
  return false;
 }
 return key == ((ReusableKey)o).key;
}
}


Reply via email to