HashCode method

How to write overridden hashcode method? Is there any particular rule for it?

Folks,
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. My two bobs worth is... I'm a simple kind of idiot... I struggle with all the double negatives in Object.hashCode API. So here's my rewrite.
The equals and hashCode methods share a special relationship.
The general contract is:
1. If two objects are equals they must have the same hashCode.
2. BUT, If two objects have the same hashCode they don't necessarily have to be equals, but this is called "a hashCode clash", which ain't good. A poor hashCode implementation (one which produces a high proportion of "clashes") dramatically slows-down hashMap lookups. In hash-code-land: More distincter is more betterer.
3. Both equals and hashCode must be consistent over time. The hashCode must remain unchanged unless an attribute effecting equals has changed... at which time the hashCode proabably should change (but see rule 2).
The rules of thumb for developers are:
1. The equals and the hashCode methods should examine the same attributes of the object.
2. So... If you override hashCode you almost certainly need to override equals to fulfill the above contract.
2. And vice versa: If you override equals you probably need to override hashCode to fulfill the above contract.
And what the API should say but doesn't is that hashCode only affects Hash* collections (those which begin with the word "Hash") such as HashTable, and HashMap. If you're not using Hash* collections (and are positive that your objects will never be stored in a Hash* collection) then you can get away with totally ignoring hashCode and all of it's innate complexities; with the Caveat Emptor that surety is inversely proportional to the magnitude of the universe of discourse... so you're better off just doing it, coz it's easier than evaluating the consequences of NOT doing it.
Just my two bobs worth.
Cheers. Keith.

Similar Messages

  • Why should we overide hashCode method when we overide equals ?

    Why should we overide hashCode method when we overide equals ?

    java.lang.Swapnil wrote:
    Why should we overide hashCode method when we overide equals ?For the purpose of hashing, you need to override both hashcode and equal method. It is because different objects(in most cases) have different hashcode.
    Edited by: Hunky322 on 28.?ub.2009 16:21

  • Comparing dynamic fields of objects using equals and hashCode methods

    To compare the different objects of the same class with their contents like jobTitleId, classificationId, deptId & classificationId was to be done and do some manipulations later using Set and Map. I was able to do that by simply overriding the equals and hashCode methods of Object class and was able to fetch the information (like in the following Map).
        Map<LocationData, List<LocationData>>
    The following is the class I used (its been shown to you so that it can be referred for my problem statement):
    LocationData class
        package com.astreait.bulkloader;
        public class LocationData {    
            String locId, deptId, jobTitleId, classificationId;
            @Override  
            public boolean equals(Object obj) {        
                LocationData ld = (LocationData)obj;       
                return this.deptId.equals(ld.deptId) && this.jobTitleId.equals(ld.jobTitleId) && this.classificationId.equals(ld.classificationId) &&
        this.locId.equals(ld.locId);   
            @Override  
            public int hashCode() {        
                return deptId.hashCode() + jobTitleId.hashCode() + classificationId.hashCode() +locId.hashCode();  
    Problem:
    I'm already known to which all fields of this object I need to make the comparison.
    i.e I'm bound to use the variables named classificationId, deptId, jobTitleId & locId etc.
    Need:
    I need to customize this logic such that the fields Names (classificationId, deptId, jobTitleId & locId etc) can be pulled dynamically along with their values. So, as far as my understanding I made use of 2 classes (TableClass and ColWithData) such that the List of ColWithData is there in TableClass object.
    I'm thinking what if I override the same two methods `equals() & hashCode();`
    such that the same can be achieved.
        TableClass class #1
        class TableClass{
            List<ColWithData> cwdList;
            @Override
            public boolean equals(Object obj) {
                boolean returnVal = false;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be compared
                return returnVal;
            @Override
            public int hashCode() {
                int returnVal = 0;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be found for their individual hashCodes
                return returnVal;
    ColWithData class #2
        class ColWithData{
            String col; // here the jobTitleId, classificationId, deptId, locId or any other more fields info can come.
            String data; // The corresponding data or value for each jobTitleId, classificationId, deptId, locId or any other more fields.
    Please let me know if I'm proceeding in the right direction or I should make some any other approach. If it is ok to use the current approach then what should be performed in the equals and hashCode methods?
    Finally I need to make the map as: (Its not the concern how I will make, but can be considered as my desired result from this logic)
        Map<TableClass, List<TableClass>> finalMap;

    Hello,
    What is the relation with the Oracle Forms tool ?
    Francois

  • HashCode method execution

    Dear Members :
    I have custom hashCode method in conjunction with overriden equals method, in my program and have following doubts/observations :
    [1] In order to verify whether the hashCode method is executed, I put a println statement within method, but this doesn't output when the program is run.
    [2] The program is a simple equality testing of two dates and doesn't make use of any map. I want to know when and who gives (implicit ?) call to this hashCode method, when equals method is overriden, I mean the program flow.
    Since SUN suggests to override hashCode, whenever equals method is overriden, and my program is not making use of map, how and when the hashCode method gets called and if so why my test print is not executed ?
    Thanks in advance.
    Atanu

    uj_ wrote:
    jverd wrote:
    uj_ wrote:
    One way to graciously avoid the contract is to override hashCode and let it throw an exception (or assertion) stating "hashCode not implemented. This class is not intended for use in hash-based collections" or something.What would be the advantage of doing that over just taking the 5 minutes needed to implement it properly?Who are you to stipulate other people's design needs? Just because something takes just 5 minutes doesn't mean it's the right thing to do.
    You may want a class to have an equals relation based on content but you still may not want the class to be in a hash-based collection. The most compelling reason may be that it's not immutable.
    The equals/hashCode contract is mostly a Sun promise regarding "standard" classes. Everybody else design their classes the way they see fit.Calm down UJ. I have as much right to offer my opinion as you have to offer yours. I just asked a simple question.
    The requirement that a class not be used in a hash-based collection would be silly. It's up to the user of the class how to store instances. If the fields that go into determining hashCode are mutable, then that should be a documentation issue. There are good reasons to keep hashCode and equals in sync. The only reason not to do so would be the time it takes to write the code. Since that time is trivial for any well-designed class, it's an extremely weak reason.

  • HashCode() method implementation in KVM

    hi, I've got a problem with the KVM implementation of Object.
    More specifically I verified that Class Objects change their hash codes during a run session of the same VM which seems to be a violation of the rule
    Whenever it is invoked on the same object more than once during
    an execution of a Java application, the hashCode method
    must consistently return the same integer, provided no information
    used in equals comparisons on the object is modified.
    written in the Object class doc
    Suppose I define a class named MyClass. At different times during the execution of my application I may end up writing the following code.
    Object obj1 = new MyClass().getClass();
    System.out.println(obj1.hashCode());
    // Sometime elapses
    Object obj2 = new MyClass().getClass();
    System.out.println(obj2.hashCode());
    System.out.println(obj1 == obj2);What I see in the print out is that the two hashcodes are sometime different while the two objects references exactly point to the same Object consistently returning true as it should be.
    Any hint for this misbehaviour?

    Hey Hi,
        This method determines which entries are offered for selection in the
        dropdown list box for the salary statement. Entries can include, for
        example:
        o   All Salary Statements
        o   3 Salary Statements
        o   6 Salary Statements
        For each entry available for selection, you must specify the sequence
        number of the oldest salary statement displayed in the hit list for
        selection.
        As before, you define the standard selection for this selection list.
    The following export parameters are available:
    Parameter      -      Description
    EX_MESSAGE -          Message
    EX_VALUE_SET_EXT-     ESS: Enhanced ValueSet Structure
    EX_DEFAULT_ENTRY -    Default entry in dropdown list
    INCLUDE HRXSS_SER_VALUE_SET (ESS: Extended Value-Set Structure )
    is nothing but the structurr which has following componants or you can say fields
    VSKEY
    VSVALUE
    SEQNR
    During the RUN times this fields can hold the value and export it to the portal as the Bussiness logic.

  • The hashCode() method

    As per the Java API documentation, the hashCode method returns distinct integers for distinct objects. In my code, which used this method for generating unique ids for a large number of objects, I came across a duplication of ids generated (i.e. the int returned by hashCode()).
    Is it possible for two different objects to have same values returned when hashCode method is invoked?
    Can any one please tell me where I can find the implementation code/detailed logic for this Java method?
    JRahul

    With the Identifiable interface.
    As the implementation of getID() should be the same in all of your class where you want to be able to get an unique ID, you could also either defines a abstract class instead of a interface, or create a parent implementing getID() and from which your classes may inherit.
    But in such cases, you cannot extends others class into yours.
    public class UniqueIDTest {
         private final int NUM_INSTANCE = 10;
         private final int NUM_CALL = 5;
         public UniqueIDTest() {
              UniqueID[] uniqueID = new UniqueID[NUM_INSTANCE];
              for (int i = 0; i < NUM_INSTANCE; i++) {
                   uniqueID[i] = new UniqueID();
              for (int i = 0; i < NUM_INSTANCE; i++) {
                   for (int j = 0; j < NUM_CALL; j++) {
                        System.out.println(uniqueID.getID());
         public static void main(String[] args) {
              UniqueIDTest uniqueUDTest = new UniqueIDTest();
    public class UniqueID implements Identifiable {
         public UniqueID() {     }
         public int getID() {
              return IDGenerator.getID();
    public class IDGenerator {
         private static int id = 0;
         private IDGenerator() {} //To avoid instanciation
         public static synchronized int getID() {
              return id++;
    public interface Identifiable {
         public int getID();

  • Overriding hashcode method

    Can u pls tell me friends why should definetly i override the hashcode method if i override equals method of the Object class

    Because the contracts of equals and hashCode are strongly bound to each other.
    For each objects x and y where x.equals(y) returns true x.hashCode() must be equal to y.hashCode().
    If you don't follow this convention you'll get hard-to-find bugs as soon as you use your object as a key in some kind of HashMap/HashTable/...

  • HashCode method return same value for different string?

    Hello. I am finding hashCode method of string return same hashcode for many different string? It seem when string is long we get same value many times? What is solution? I am useing JDK 1.0.2. Thank you.

    Hello. I am finding hashCode method of string return
    same hashcode for many different string? There are about 4 billion possible hashcode values.
    How many possible strings do you think there are?
    Obviously many strings will have the same hashcode.
    What is
    solution?The solution is to not depend on hashcodes being unique.

  • Class HashSet and hashCode method

    I'm using a HashSet class with elements of class A.
    I define the equals method but when i add a object which is already in the set, this object is duplicate.
    Do i have to define the hashCode method in the class A? If yes, i don't understand why this method is used when adding a object.
    Can you give me a explanation ?

    Yes, you do. The hashCode method is used by HashSet and HashMap to find an object. See the API doc for Object, which explains the relationship between equals and hashCode.

  • Override hashCode() method

    hi,
    I'm writing a very simple hashCode() function (3different way), which uses 2 string to calculate the hashCode, it looks somethings like this:
    1)...
    public int hashCode() {
    str1 = "abc"; //Can be replaced by any string
    str2 = "cde"; //Can be replaced by any string
    return (str1 + str2).hashCode();
    }2...
    public int hashCode() {
    str1 = "abc"; //Can be replaced by any string
    str2 = "cde"; //Can be replaced by any string
    return (str1 + "-----" + str2).hashCode();
    }3...
    public int hashCode() {
    str1 = "abc"; //Can be replaced by any string
    str2 = "cde"; //Can be replaced by any string
    return (str1.hashCode() + str2.hashCode());
    }For 1 (similar for 2) if we have str1 + str2 = str1' + str2', then it will returns the same hashcode, which is I dont want...
    But for 3, will that results in clustering? What are the bad things about 3?
    Thanks

    I don't have any problem at the moment, I am just asking for opinion on the good and bad thing of each of those implementation on hashCode().
    My equals() methods is pretty obvious, if str1 = str1' and str2 = str2' then return true.
    The str1 & str2 can change.
    Anyway, let me put in the whole class code:
         public class MyClassTest {
              private final String str1;
              private final String str2;
              public MyClassTest(final String s1, final String s2) {
                   str1 = s1;
                   str2 = s2;
              public String getStr1() {
                   return str1;
              public String getStr2() {
                   return str2;
              public boolean equals(Object anotherMyClassTest) {
                   if (anotherMyClassTest instanceof MyClassTest) {
                        MyClassTest id = (MyClassTest) anotherMyClassTest;
                        if (id.getStr1().equals(this.getStr1()) && (id.getStr2().equals(this.getStr2()))) {
                             return true;
                   return false;
              public int hashCode() {
                   //See the 3 implementation below
         }and then, there was three way of implementing the hashCode()
    1)...
    public int hashCode() {
    return (str1 + str2).hashCode();
    2...
    public int hashCode() {
    return (str1 + "-----" + str2).hashCode();
    3...
    public int hashCode() {
    return (str1.hashCode() + str2.hashCode());
    }This MyClassTest will then be used inside a HashMap as the key (and there can be many of these)
    And my question is: Which of the 3 implementation is the best, and could you explain to me the good/bad thing of each of those 3 implementation?
    Thanks
    Message was edited by:
    Gurluver
    Message was edited by:
    Gurluver

  • Why Collection interface declares equals() and hashCode() method

    When I went through the source code of Collection interface, I found equals() and hashCode() are declared? Why? If a class implements this interface, it will inherit these two method from Object, and we can true to override them.

    It's probably so that they can provide the documentation that you see there.

  • HashCode() method and identityHashCode() difference

    Hi to All
    I am working in Java Strings. While studying java Strings, I am getting confusion to understand what is hashCode() and identityHashCode() method. I have written a small program and executed. I got two different out puts. Here i am posting my code.
    public class StringDemo {
         public static void main(String[] args){
              String str="Hello";
              System.out.println(str.hashCode());
              System.out.println(System.identityHashCode(str));     
    When i have run the above program i got the following out puts
    *69609650*
    *14978587*
    The first one is generated by hashCode() and second one is by identityHashCode(). Can any one explain me what are those two different nos. Thanks in advance.

    user10137999 wrote:
    The first one is generated by hashCode() and second one is by identityHashCode(). Can any one explain me what are those two different nos. Thanks in advance.You read the docs for Object.hashCode(), Object.identityHashCode(), and String.hashCode(), right? After reading those docs, what part did you not understand?

  • Help need to know hashcode() and Equals method

    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........

    jverd wrote:
    euph wrote:
    jverd wrote:
    euph wrote:
    REFTY5_ wrote:
    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........Thery're asking you to override the equals and hashCode methods. Override means replace.So does "overwrite." However, as you point out, "override" is the correct word here.So you think "overwrite" means the same as "replace"?To the same extent that "override" does. But both are in the general sense. Override has a specific meaning in this Java context, and overwrite does not.Don't tell me. That's what I said in my original reply.
    To my ear it doesn't. To me "overwrite" means the original is destroyed, whereas when something is "replaced" the fate of the original is unknown. So I think there's a slight semantic difference between these words.Fair enough.Fair enougth, but the next time I suggest you're better sorted.

  • When we override Hashcode and Equal Methods

    Hi....I have doubt regading Hashcode and equal methods
    why we override this two methods....
    why we override hashcode method when we are overriding equal method,
    i would very thankful to give answser
    Thank you
    Ramesh

    hash code is computed to check the equality of two
    objects ,
    that is why if u change the default equal method
    implementation , u need to change the hashcode method
    as well.That's an incomplete answer at best.
    The hashcode method is used by hashing algorithms and data strcutures such as HashMap. This value is used to determine what 'bucket' the reference will go into. It cannot, by itself determine equality.
    If you are still unsure, I suggest looking up 'hash table' on google. I'm sure there's a decent explanation on wikipedia.

  • Hashmap containsKey() method does not appear to work

    Hashmap containsKey() method does not appear to work
    I have an amazingly simple custom class called CalculationKey, with my own amazingly simple custom equals() method. For some reason when I call my containsKey() method on my HashMap it does not use my defined equals method in my defined key class. Do hashmaps have their own tricky way for establishing whether two keys are equal or not?
    THIS IS MY AMAZINGLY SIMPLE CUSTOM KEY CLASS
    private class CalculationKey
    private LongIdentifier repID;
    private LongIdentifier calcID;
    public CalculationKey(LongIdentifier repID, LongIdentifier calcID)
    this.repID = repID;
    this.calcID = calcID;
    public boolean equals(Object o)
    CalculationKey key = (CalculationKey)o;
    if (key.getCalcID().equals(calcID) &&
    key.getRepID().equals(repID))
    return true;
    else
    return false;
    public LongIdentifier getCalcID()
    return calcID;
    public LongIdentifier getRepID()
    return repID;
    THIS IS MY AMAZINGLY SIMPLE CALLS TO MY HASHMAP WHICH ADDS, CHECKS, AND GETS FROM THE HASHMAP.
    private Hashmap calculationResults = new Hashmap();
    public boolean containsCalculationResult(LongIdentifier repID, LongIdentifier calcID)
    if (calculationResults.containsKey(new CalculationKey(repID, calcID)))
    return true;
    else
    return false;
    public Double getCalculationResult(LongIdentifier repID, LongIdentifier calcID)
    return (Double)calculationResults.get(new CalculationKey(repID, calcID));
    public void addCalculationResult(LongIdentifier repID, LongIdentifier calcID, Double value)
    calculationResults.put(new CalculationKey(repID, calcID), value);
    }....cheers

    You can make a trivial implementation to return a
    constant (not recommended)What do you mean by that? Hmm.. I guess you mean that
    you shouldn't use the same constant for all objects?
    But don't see the int value of an (immutable) Integer
    as constant?
    /Kaj
    You can write hashCode to just always return, say, 42. It will be correct because all objects that are equal will have equal hashcodes. Objects that are not equal will also have equal hashcodes, but that's legal--it just causes a performance hit.
    The value is that it's really really simple to implement: public int hashCode() {
        return 42;
    } So you can use it temporarily while you're concentrating on learning other stuff, or during debugging as a way to confirm that the hashCode is not the problem. (Returning a constant from hashcode(), rather than computing a value, is always legal and correct, so if something's behaving wrong, and you replace your hashCode method with the one above, and it still breaks, you know hashCode isn't the problem.)
    The downside is that you're defeating the purpose of hashing, and any non-trival sized map or set is going to have lousy performance.
    For a decent hashCode recipe, look here:
    http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf

Maybe you are looking for

  • Total in alv report

    hi everyone! there is an alv report  that runs correctly in dev system and shows the totals in the alv report. when the request is being transport to qa system, the alv report doesn't shows the totals line at all. i tried to transport the report seve

  • New Write up transaction type which can post to Affiliated company

    Hi Gurus,   Can you please help me with this request. I have been asked to create the New Write up transaction type which can post to Affiliated companies copy  of transaction type 700.   But i dont see any such option (Posting type) in transaction A

  • Who's Who : does not at all show of "Placeholder" of Photo

    Dear Experts We have SAP_ESS with 600 SP16    on   SAP NW 7.00 SP20  Java System (inlcudes Application Server Java + Enterprise Portal + Enterprise Portal Core Components) When we browse thry SAP Standard " Who's Who" - It just display the employee i

  • Field displays in PDF but not in Designer

    I have a field that shows up in the PDF version of the form, but I cannot see it to delete it in Designer. Any good ideas how to get to that field? I tried moving stuff to the back and moving adjacent fields around, but the field does not show up in

  • GTK 2.0 issues? [solved]

    Well, ever since the new gtk 2.0 came out the buttons don't look how a theme should, they are always embossed. Last edited by twiistedkaos (2007-02-22 00:52:29)