Why hashcode

What is the use of hash code () method?

hashCode is used as a fast way to compare two objects.
If the hashCode are equal, there is a chance that the
two objects are equal. This is then verified by
calling the equals method.
It is used a lot with the Collection classes, for
example with the HashMap. The HashMap will not allow
duplicate keys, so when you add something, it checks
if the key already exist, and if it does it overrides
the value.This is true, but only upto a point.
It depends on the way the hash code is generated.
The hashcode for java.lang.Object is based on the actual reference (read: pointer value) for that object and you can test for identity when using the standard hash code values but not for probable equality.
This kind of test for identity or probable equality is not reliable however. It is often recommended that you override the equals and hashcode methods for classes so that things like the Collections classes handle instances of your classes in a predictable manner. This can mean that using hash code comparison as a clue to possible equality can often cause you to take an extra step in checking for equality when this would not be the case (reason, you normally check for class equality with instanceof and then equality. The hashcode step can work, see below).
Using hashcode for probable equality checks will only work properly, after instance class comparison, if the hashcode reflects the uniqueness of those member variables for the purposes of comparison.
The problem with this usage of hashcodes is that it can cause clumping of keys inside datastructures like the Hashtable collection class where hashcode is used for working out which 'bucket' the key should land in. This leads to poor performance in your collection as the less uniform the key distribution is the more time it takes to actually find the key you want in the bucket.
In short:-
hashcode should normally be overriden to optimise the distribution of keys in Collections,
equals should be overriden to ensure proper equality and also allow you to optimise the method, instance class equality, primitives then object member equality.
Example
class Simple {
    int a = 1;
    String b = "I am a String";
    public boolean equals(Object ob) {
        return (ob instanceof Simple.class &&
                   this.a == ((Simple)ob).a &&
                   this.b.equals(((Simple)ob).b)); // Casts will be optimised out for the optipurists
    public int hashCode() {
        return this.a ^ this.b.hashCode();

Similar Messages

  • How to override hashcode() in String

    I need to override the hashcode() method in java.lang.String with a cyclic shift hash code. how do I do this? String is final so I cannot extend it. I've looked at all the postings regarding the logic of why hashcode() must be overwritten with equals() etc, but I need some thoughts on how to actually override the method.

    public class MyString { // you are right, you can't extends java.lang.String
      private String str; // but you can wrap it
      public MyString(String s) {
        this.str = s;
      public String get() {
        return this.str;
      // ... implement all or most String methods again ...
      // ... then ...
      public int hashcode() {
        return whatEverYouWant; // but make sure it is consistent with equals
      public boolean equals(Object obj) {
        return (MyString)obj.get().equals(this.get());
    }--lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Overriding hashCode

    When using HashSet or LinkedHashSet, the objects you add to them
    must override hashCode().[u]Why ??
    I think Object.hashCode() returns hashcode of an object and two different objects can have same hashCode.
    So if i have to use HashSet or LinkedHashSet,do i need to override hashCode() in such a way so that it provides different hashcode for different objects so as to avoid duplicate objects in a HashSet (Serving the purpose of HashSet)

    HashSet is backed by a hash table (i.e. uses the
    hashCode to organize its data), allowing
    good/constant performance for theadd/remove/contains
    methods by using (I guess) binary search (seeHashMap
    for details?)No, TreeSet and -Map use a binary search. Internally,
    they are backed up by a Red-Black tree (a
    "self-balancing" binary tree).Oh right, mea culpa, the HashSet (HashMap) uses a "direct" hashcode-to-bucket mapping, then linear search throughout the bucket (which explains why hashCode implementation/dispersion is of some importance.)

  • Why methods equals() and hashCode() is defined in Object Class?

    Why methods equals() and hashCode() is defined in Object Class?

    If you have two objects and you don't know (or care about) their exact types, but you still want to know if they are the same, then you can do something like this:
    Object o1 = getObject1();
    Object o2 = getObject2();
    if (o1.equals(o2)) {
      // they are the same, do something
    } else {
      // they are different, do something else
    }This could be useful if you were to write a generic cache, for example.
    A similar thing is true for hashCode(), if you want to manage things in a HashSet, you'll need them to implement hashCode().
    If Object didn't have those methods, then you'd have to write that code against a more specific interface/class and it wouldn't be so general any more.

  • 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

  • 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() of value called during session.setAttribute() why?

    When I set a Vector value into session hashCode() is called on the elements of the Vector? Why?
    In the code below, MyObject extends a base class that has the following implementation of hashCode() so as to enforce its implementation in all it's children if and only if it is required (i.e. not really a case for an abstract class as I want to try to avoid its implementation).
    public int hashCode () {
        throw new RuntimeException("hashCode is not supported in base class");          
    }What I find is the following code throws the hashcode exception on the 2nd set of Key1, but I dont understand why. Why is hashCode() called on the elements of the vector? is this some set optimization - i.e. it does not update session if the objects are the same?
    Vector v1 = new Vector();
    v1.add( new MyObject( someUniqueParam1 ) );
    v1.add( new MyObject( someUniqueParam2 ) );
    Vector v2 = new Vector();
    v2.add( new MyObject( someUniqueParam1 ) );
    v2.add( new MyObject( someUniqueParam2 ) );
    session.setAttribute( "Key1", v1 ); // successful
    session.setAttribute( "Key2", v2 ); // successful
    session.setAttribute( "Key1", v2 ); // exception thrown from MyObject - why?Please help me understand? My workaround for the moment is to call session.removeValue() first.

    The hashCode() method in Vector calls hashCode() in its superclass (AbstractList) which calls hashCode() on each of the objects stored in the List. It looks as if the servlet container calls hashCode() on the object being added as a session attribute when the key is already present. Why this happens is anyone's guess (checking if object is same as the one currently stored?) and is probably servlet engine specific.
    Overriding hashCode() to throw an exception is probably not a good idea as many Java classes call hashCode() "behind the scenes" which is why the default implementation is part of Object. Can you use that default implementation?

  • .hashCode() ... why?

    i understand the use of .equals() but i don't understand what the point of .hashCode() is, and im even more confused about how to implement it in my objects.. i tried something similiar to String.hashCode() but i really don't see its meaning.

    Hashcodes stand for an in-a-number-abbreviated version of an object; the total (virtual) collection of hashcodes (2^64) is implied by the total (virtual) collection of all objects; that is, all objects that are the same (and therefore return both true, when compared with the other through equals()), return the same hashcode. However, unequal objects <b>may</b> return the same hashcode, or they may not. For the sake of the proper functioning of classes like Hashtable et al, it is not very advisory to make an algorithm that returns an identical hashcode all the time, nor one that is limited to a subset of numbers. It is best for the performance of to Hashtable if the objects therein inserted are of a nice thin spread out of the numberspace of 2^64.
    <p>Why ? Because hashtables (one of the quickest algorithms of unsorted lookup that has been developed) function through the use of these. For reference http://www.sleepycat.com .
    <p>How can you make your own hashcode algorithm ? For example by adding up all the hashcodes of all your relevant members.

  • Why methods hashCode(), equals(), toString() from BaseXmlObject are final ?

    Raj, probably you know... What was the reason for that?
    I just want to use some of my XmlBeans as keys in a HashMap and tried to
    override these methods using XmlBeans extension interfaces.
    Is it still the case in WLW 9.2?
    Thanks, Denis.

    Hi Denis,
    Unfortunately, I'm unaware of the specific reason why this was done. I'd suggest emailing the XMLBean dev/user mailing list at [email protected] / [email protected]
    Regarding 9.2 behavior, I've checked the XmlBeans 2.1 documentation and it is the same.
    cheers
    Raj

  • Hashcode switch problem

    Hello. Can anyone tell me why this isn't working? I'm trying to use a switch off of a String, so I take the hashcode of it and compare it to the possible input strings. It looks like it should work, it's just comparing intergers, but my compiler always gives me an error "constant expression required". Why is this happenning?
    Here is my code:
    final int string1 = "hello".hashCode() ;
    final int string2 = "goodbye".hashCode() ;
    String input ;
    switch( input.hashCode() )
    case string1 :
    // stuff
    case string2 :
    // stuff
    }The compiler always hits the error on the 'case string1:' line. How can it say "i need a constant value" when the value it's using is a final? Isn't that constant enough?

    final int string1 = "hello".hashCode() ;
    final int string2 = "goodbye".hashCode() ;is resolved at run-time.
    switch( input.hashCode() )
    case string1 :
    case string2 :is resolved at compile-time.
    so you have to use if..else..endif; however I don't see why you would need hashCode() to compare strings.
    Maybe for performance ??? Then you should make sure that using hashCode() is really faster. otherwise you end up with VERY strange code.

  • Trying to understand hashCode( )

    Hello again, I'm trying to understand the hashCode( ) method. I have a textbook which describes it this way:
    "A hashcode is a value that uniquely identifies an individual object. For example, you could use the memory address of an object as it's hashcode if you wanted. It's used as a key in the standard java.util.Hashtable[i] class."
    Please forgive me if this emplies that I may be a bit slow with this, but this explanation is too vague for me to grasph what's going on here. Can someone thoroughly explain (in a non scientific way), how and why this method is used?
    Thanks in advance.

    I thought the examples I provided might give you an idea why the hashCode method is useful. I'll try one more brief one, and if that doesn't connect that spare wire to the light bulb over your head, then I'll have to agree with schapel and suggest that you study up on your CS theory.
    This will be a really crocked up example, and you could skirt some of the issues with better design, but it's a valid example nonetheless.
    You run a greenhouse or an arboretum or something. You've got 25,000 Tree objects (forget their subclasses for now). Trees have properties like species, name (I don't know why you'd name a tree--just bear with me), location, age, medical history. You're going to put your Trees into a java.util.Set, so you've got a collection with one reference to each tree. However, you're getting overlapping subsets of your trees from various sources--that is getAllElms() returns some trees that are also in getAllOlderThan(10). You need to combine all those results into a 1-each collection of Trees.
    When you go to add an Object to the Set, the Set has to first check if that Object is already present. The Set implementation could iterate over all its elements and call equals() to see if that Object is already there. Or, it could first get the hashCode (let's say you've implemented hashCode to return the xor of the species and the age). So, maybe 100 out of your 25,000 trees are 50 yeard old Elms. Internally, if the Set implementation keeps a mapping from hashCode to an array of Trees with that hashcode, then it only has to copmare to those 100 trees that match, rather than all 25,000.
    As I said, this is a cheezy example. One problem is that if trees are mutable, this Set implementation won't work, since the Set won't know that a Tree's internal values (and hence, possibly, its hashCode) have changed.
    Is is making any sense yet?
    Okay so please help me understand this rudimentary,
    logical reason for wanting to use a hashCode( )? Say
    I create a top level class called "Plant.java". Now
    from that class I create a subclass called Tree.java
    from which several other subclasses and objects are
    created. Help me gain a basic understanding of why
    and how the hashCode( ) method might be beneficial.
    (lol... I feel sort of like I've opened up a cool new
    electronic toy, I'm standing here with a "spare wire
    in my hand wondering what the heck this part is
    for?")
    Thanks again for your help. I really apprecitate it.

  • Why use *31L in the following code?

    Why use *31L in the following code?
    * {@inheritDoc}
    public int hashCode()
    return (int) ((long) getAreaCode() * 31L + getLocalNumber());
    public class PhoneNumber
            implements PortableObject
        // ----- constructors ---------------------------------------------------
        * Default constructor (necessary for PortableObject implementation).
        public PhoneNumber()
        * Construct a Phone.
        * @param nAccessCode   the numbers used to access international or
        *                      non-local calls
        * @param nCountryCode  the numbers used to designate a country
        * @param nAreaCode     the numbers used to indicate a geographical region
        * @param lLocalNumber  the local numbers
        public PhoneNumber(short nAccessCode, short nCountryCode,
                short nAreaCode, long lLocalNumber)
            m_nAccessCode  = nAccessCode;
            m_nCountryCode = nCountryCode;
            m_nAreaCode    = nAreaCode;
            m_lLocalNumber = lLocalNumber;
        // ----- accessors ------------------------------------------------------
        * Return the access code.
        * @return the access code
        public short getAccessCode()
            return m_nAccessCode;
        * Set the numbers used to access international or non-local calls.
        * @param nAccessCode  the access code numbers
        public void setAccessCode(short nAccessCode)
            m_nAccessCode = nAccessCode;
        * Return the country code.
        * @return the country code
        public short getCountryCode()
            return m_nCountryCode;
        * Set the country code.
        * @param nCountryCode  the country code
        public void setCountryCode(short nCountryCode)
            m_nCountryCode = nCountryCode;
        * Return the area code.
        * @return the area code
        public short getAreaCode()
            return m_nAreaCode;
        * Set the numbers used indicate a geographic area within a country.
        * @param nAreaCode  the area code
        public void setAreaCode(short nAreaCode)
            m_nAreaCode = nAreaCode;
        * Return the local or subscriber number.
        * @return the local or subscriber number
        public long getLocalNumber()
            return m_lLocalNumber;
        * Set the local or subscriber number.
        * @param lLocalNumbeer  the local or subscriber number
        public void setLocalNumber(long lLocalNumbeer)
            m_lLocalNumber = lLocalNumbeer;
        // ----- PortableObject interface ---------------------------------------
        * {@inheritDoc}
        public void readExternal(PofReader reader)
                throws IOException
            m_nAccessCode  = reader.readShort(ACCESS_CODE);
            m_nCountryCode = reader.readShort(COUNTRY_CODE);
            m_nAreaCode    = reader.readShort(AREA_CODE);
            m_lLocalNumber = reader.readLong(LOCAL_NUMBER);
        * {@inheritDoc}
        public void writeExternal(PofWriter writer)
                throws IOException
            writer.writeShort(ACCESS_CODE, m_nAccessCode);
            writer.writeShort(COUNTRY_CODE, m_nCountryCode);
            writer.writeShort(AREA_CODE, m_nAreaCode);
            writer.writeLong(LOCAL_NUMBER, m_lLocalNumber);
        // ----- Object methods -------------------------------------------------
        * {@inheritDoc}
        public boolean equals(Object oThat)
            if (this == oThat)
                return true;
            if (oThat == null)
                return false;
            PhoneNumber that = (PhoneNumber) oThat;
            return getAccessCode()  == that.getAccessCode()  &&
                   getCountryCode() == that.getCountryCode() &&
                   getAreaCode()    == that.getAreaCode()    &&
                   getLocalNumber() == that.getLocalNumber();
        * {@inheritDoc}
        public int hashCode()
            return (int) ((long) getAreaCode() * 31L + getLocalNumber());
        * {@inheritDoc}
        public String toString()
            return "+" + getAccessCode() + " " + getCountryCode() + " "
                       + getAreaCode()   + " " + getLocalNumber();
    ...

    31 is a nice prime number that is used here to decrease hash collisions
    thanks,
    -Rob

  • Please help me in understanding hashcode()

    I have some doubt with hashcode(), please help me in understanding.
    As it is always advised that whenever you override equals() method, override even hashcode(). As equals() returns the equality of two objects i.e it returns whether two objects are equal or not. The hashcode(), returns int value, i.e if two objects are equal than both hashcode will be same.
    Now my question is:
    1. When equals() method is comparing 2 objects and returning whethere both are equal or not. Then why we need this hashcode().
    2. When this hashcode(), is going to be call?
    Please tell me Whatever I understood is right or not....

    rajalakshmi wrote:
    2. When this hashcode(), is going to be call?
    equals() method will implicitly call hashCode() method to compare objects.No it won't. Where did you get that?
    Here is the actual code to Strings equals method
        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) {
              char v1[] = value;
              char v2[] = anotherString.value;
              int i = offset;
              int j = anotherString.offset;
              while (n-- != 0) {
                  if (v1[i++] != v2[j++])
                   return false;
              return true;
         return false;
        }Now, where is hashCode called there?

  • Use of hashCode and equals method in java(Object class)

    What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.

    You could find that out easily with google, that is a standard junior developer interview question.

  • Float Arrays and hashcodes

    Hi,
    I have some problems with generating unique hash codes for float arrays.
    The following code will result in "true" on my JVM (JRE 1.6):
    System.out.println(Arrays.hashCode(new float[]{0,1,2,3,6,9}) == Arrays.hashCode(new float[]{0,1,3,6,8,9}));Does anyone have an idea how to generate a truly unique hashcode for float arrays?
    Thanks for your help,
    Dieter

    JoachimSauer wrote:
    dkleinrath wrote:
    JoachimSauer wrote:
    But again: you don't usually need a perfect hash. Why do you think you need one?I use static HashMaps to store meta information about specific arrays. I also use a HashSet to search for unique arrays in a big collection of arrays.That's ok. Both HashMap and HashSet can work perfectly with in-perfect hash code (obviously, since perfect hash codes are not possible in many situations).
    What they can not handle is .equals() being "wrong" (i.e. inconsistent with hashCode()).
    This means that you can't directly use float[] as keys.
    You could build a simple wrapper around float[] to be used as keys, 'though.I just tried that and it works like a charm.
    Thank you very much for your help.

Maybe you are looking for

  • Ipad 2 Print button does not work after 6 upgrade?

    Since we upgraded to iOS6, our print button does not work and does not find our printer.  It was working fine until iOS6.  Called an Apple Technician and he had me reset, which wiped out all of my saved information but didn't fix the print.  He then

  • "Live Tile" Background on Mac

    What I'm looking for is a way to have a changing tile background on my laptop and desktop Mac's. What I'm imagining is similar to the "Shifting Tiles" screensaver on the Apple TV. I know I can set the backgrounds to change/rotate on a given interval,

  • FI- Vendor Invoice PARK

    Dear All, I want FM/BAPI/IDoc for PARK FI Vendor Invoice just like TCode FB60. Actual scenario is that i want to send Invoice detail from an external system which contain details without PO and want to see in SAP as PARK Invoice and that can be POSTE

  • URGENT:Problems with OJMS

    Hi, I have a problem with OJMS and MDBs. The problem is that I receive messages correctly, but messages are not dequeued from database. I have followed MDB's developer guide from oracle, the only difference is that I'm using stardard JMS interface in

  • 3D function in Photoshop CC doesnt work

    Hello, I can not use the 3D function in Photoshop CC, as these appear as grayed out button. I have Asus Notebook Win 8.1 Intel Core i3 Nvidia Geforce GT 720m Have the requirements of the graphics card, via the Control Panel, focusing on Photoshop, bu