-1

Possible Duplicate:
Hashcode and equals

I have read many articles about hashcode and equals and their relations ship. So far my understanding is every object has equals and hashcode function by default .As java class has those functions. Now hashcode means it returns the memory address of an object.hashcodes are unique by default .When a object is created you will get a unique has code.

  • Now my question is when you override the equals function as per rule we need to override the hashcode function..?
  • So is that we implement the hashcode function along with equals method but the hascode implementation is of no use..?
  • And how the hashcode is used in hashmap and hashtable of collection framework..?

    class person{
    
       string name;
    
       string employer;
    
       boolean equals(Object o){
          person per=(person)o;
          if(per.employer==this.employeer){    
              return true
          }
          return false;
      }  
    
      int hashcode(){
    
          return 0;//what ever i do in hashcode does it really effect any thing..as the equals does                
                   //the comparison for me and gave me the result     
      }
    
    }
    

and how the hascodes are used in hashmap and hashtable

Thanks,

Community
  • 1
  • 1
swati
  • 2,099
  • 6
  • 19
  • 23

2 Answers2

1

Read Chapter 3 of Joshua Bloch's "Effective Java":

http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

It tells you how to write both properly.

You ought to know that keys in Maps ought to be immutable. That's true in every language that supports maps/dictionaries: Python, Java, C#, etc.

duffymo
  • 305,152
  • 44
  • 369
  • 561
1

I asked a very similar question for C#, and I suspect the correct answer is about the same.

Bottom line in my view (see answers to my question for some conflicting viewpoints) is that it's up to your application domain to decide whether an object having exactly equal properties to another object should mean that they are "equal", or whether two objects with different addresses (but exactly the same property values) are inequal.

I would tend to stay with the far more common definition that objects with the same property values but different addresses are in fact different. If you feel you need to use the other definition, it must be extremely clear to everyone on the team that a) that is the convention, and b) why that is the convention, or bad bugs are quite likely to pop up.

Further, any time an object participates in a collection (such as a dictionary) that relies on the hash code to find that object, the hash code must be stable for the duration of time that the object participates in that collection.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553