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.

Similar Messages

  • 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.

  • Do I need to override enum's hashCode() and equals()?

    Hi all:
    I have a enum type let's say it is
    public enum Type
      ONE,
      TWO;
    }If I want to compare the enum value to see if they are same value or not, let's say I have two:
    Type a = Type.ONE;
    Type b = Type.TWO;should I use a.equals(b) or (a == b) If I want to use it as another class's key field, and I want to override this class hashCode() and equals() methods.
    Can enum Type return the correctly hash code?
    For example the class is like:
    public Class A
      Type type;
      pubilc boolean equals(Object other)
        // here skip check class type, null and class cast
        if(other.type.equals(this.type))
           return true;
        else
         return false;
      public int hashCode()
        int result = 31;
        result += 31 * result + type.hashCode() ;
       // can we get correct hash code from enum here?
        return result;
    }

    Answered by the test code by myself.
    We can use either equals or (==) to see if they are the same value.
    The enum's hashCode() use System.identityHashCode() to generate the hashCode and they are always correct

  • Method Overriding-toString(),hashCode() and equals()?

    Hi,
    In some Java Classes, I saw that
    toString()
    hashCode()
    equals()
    these 3 methods of Object Class is overloaded.
    I don't understand why and in what situation we have to override these 3 methods of Object Class.
    Thanks in advance for ur Knowledge Sharing.
    Regards,
    S.Prabu

    toString() is typically overridden in subclasses so as to output something useful about a class like instance variable values instead of just a hashvalue representing the object reference as per Object.
    hashCode() and equals() are overridden typically for use within the collections framework though you need to fully understand the hashing contract before starting to override these as they can cause strange results if not overridden correctly.
    Take a look at collections and specifically the hashing functionality of HashMap and HashSet for more info on these.

  • Scenario in which implement or Write our own hascode and equals method

    Dear All,
    Please let me know in which circumstances we write our own Hashcode method and equals method not the default one provided by java.Kindly give me complete code and scenario.
    Thanks
    Sumit

    Thanks for your reply
    I have one more question.
    When equal method of Object class give the same result as equals we override then why should we override equals.For example see the below code
    public class EqualsTest{
    public EqualsTest() {
         super();
    public static void main(String[] args) {
    Moof one =new Moof(8);
    Moof two =new Moof(8);
    if(one.equals(two))
    System.out.println("one is equals to two");
    class Moof {
    private int moofvalue;
    Moof(int val){
    System.out.println("val inside moof constructor"+val);
    moofvalue=val;
    System.out.println("moofvalue inside moof constructor" +moofvalue);
    public int getMoofValue()
    System.out.println("moofvalue inside getmoffvalue method "+moofvalue);
    return moofvalue;
    public boolean equals(Object o)
    System.out.println("Object o in equals"+o);
    if( (o instanceof Moof) &&(( (Moof)o).getMoofValue()==this.moofvalue))
    System.out.println("true");
    return true;
    else
    System.out.println("false");
    return false;
    Here the output we get is :
    val inside moof constructor8
    moofvalue inside moof constructor8
    val inside moof constructor8
    moofvalue inside moof constructor8
    Object o in equalsMoof@119c082
    moofvalue inside getmoffvalue method 8
    true
    one is equals to two
    The last output "one is equals to two" gives the same result as overridng equals by us.So why should we override equals here.
    Thanks
    Sumit

  • Can we use Call transaction and session method in same program ?

    Hi experts,
                     Is it suggested to use call Transaction and session method in the same Program ?
                     i have a doubt , why cant we use multiple call transactions in same program instead of session method if we have multiple transaction updations ?

    Hi Dengyong Zhang,
    we can use the call transation and session method in same program.
    However for better performance it's benificial to use call trasaction method of BDC. but if u want to upload very large amount of data then Session method is more preferable to use.
    Session method is one of the method of BDC.
    U can also use BAPI to upload the data in SAP but it's a different concept than BDC. Performance wise BAPI is more advantageous than BDC.

  • How to use line wrapping and line spacing in java?how to use line wrapping

    how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?

    Hello,
    You should post your question at:
    http://java.forum.sun.com
    Thanks
    - Rose

  • How to use line wrapping and line spacing in java?

    how to use line wrapping and line spacing in java?

    Hi,
    This is explained in the java Tutorial. Please see the link:
    http://java.sun.com/docs/books/tutorial/i18n/text/line.html
    and find some sample examples.
    Hope this helps,
    --Sun/DTS                                                                                                                                                                                                                                                                                                                                                                                       

  • I have a VI A. I want A to call another VI B and execute. After B executes, I want it to close automatically and go back to A. Is this possible ? I tried using open reference and those methods, but I am not able to do it. Can someone help me ? Thanks !

    Thanks !
    Kudos always welcome for helpful posts

    Re: I have a VI A. I want A to call another VI B and execute. After B executes, I want it to close automatically and go back to A. Is this possible ? I tried using open reference and those methods, but I am not able to do it. Can someone help me ? Thanks !Hi Stephan ! Thanks ! I guess I explained my question not so right. I've created a customized menu and at the instance of me selecting a menu, a VI should load itself dynamically. I am using call by reference. Sometimes it works and sometimes it won't. In short, what I want to achieve is load VIs dynamically and close them dynamically once they finish executing. Thanks !
    Kudos always welcome for helpful posts

  • ToString array and equals method

    I have an array and i need to get the toString to output the information. How do I get that to happen. This is what i ahve so far.
       public String toString(){
              //should indicate all cities
              System.out.print("Cities :");
              for (int i = 0; i < cities.length -1; i++)
                   return cities;
    Here is another piece of code I am finishing. Please tell me if the loop and equals method is correct but what is the value to return?
       public City getCity(String cityName){
              //returns the City with name cityName (must search for city in the array)
              //if the city does not exist, it returns null
              for(int i = 0; i < cities.length; i++)
                   if(cityName.equals ("cityName"))
                        return ;
                    else return null;
                Message was edited by:
    ehj3000

    great my world class is fixed now im getting missing return statements on the two methods
           public City getCity (String cityName){
          //returns the City with name cityName (must search for city in the array)
          //if the city does not exist, it returns null
             for(int i = 0; i < cities.length; i++)
                if(cities.getName().equals(cityName))
    return cities[i];
    else
    return null;
    public String toString(){
    //should indicate all cities
    System.out.println("Cities: ");
    for (int i = 0; i < cities.length -1; i++)
    return cities[i].getName();

  • Tool to create Java Object classes using the Database Tables

    Hi,
    Is their any tools or utility available to create the Java Object Classes using the Database Tables as input.
    Lets Say I am having the Employee, Employee_Salary tables in the Database.The utility has to create the Java Object classes with the relation.
    Please Help...
    Thx..

    Hm, for generating regular Java classes I wouldn't know one from memory. But I suggest you start searching in for example the Eclipse marketspace for a third party plugin that can do it. If all fail, you could always use Hibernate Tools from the Jboss Tools Eclipse plugin set to generate Hibernate/JPA entities and then strip the annotations from them to turn them into regular POJO classes.
    How many tables are we talking about anyway? It might be less effort to just create the classes with properties and then use an IDE to generate getters and setters for them.

  • Thread Methods but in Object class, y?

    Why wait, notify, notifyall methods are in object class instead of Thread class?

    thechad wrote:
    It's not clear to me why. Probably it's a historical artefact .. once it was in Object, it's hard to take it out.
    You're question is a fair question it seems to me. Maybe someone will tell you there's a good reason.Yes, there is a very good reason and it's not a historical artifact.
    wait / notify are used for locking in java. For instance, imagine you have a job queue, and you've got a whole bunch of worker threads that are getting jobs from it. What happens when the queue is empty and there are no more jobs? You want to wait for the queue to have more jobs. Then when a new job comes in, you want to notify any thread waiting that it can now proceed.
    In fact, with reference to why isn't this just handled in thread, it is dangerous and wrong to call wait, notify or notifyall on a Thread object... Thread.join calls wait on the thread and thread death calls notifyAll, but API docs don't guarentee this so you should avoid these methods in a Thread object.

  • Why do we need to override Hascode and Equals method?

    Hi,
    == checks if the two references are equal and .equlas will check if the value is same, if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).
    Please someone elaborate on this and also tell me what role hashcode plays in this.
    thanks
    Anirudh

    anirudh1983 wrote:
    if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).Many equals() methods do run an '==' check first for efficiency (and I would recommend it if you're writing one yourself).
    Please someone elaborate on this and also tell me what role hashcode plays in this.The reason that it is good practise to override equals() and hashCode() together is to maintain consistency.
    Hashcodes are used by all Java collections that contain the word 'Hash' in their name, and may also be used by other programs that need a hash code for identification; so if you supply one, you must follow the rules (which you can find in the API for Object.equals() and Object.hashCode()).
    The main rule is this: *objects that are equal() must have equal hashcodes*.
    Note that the reverse is NOT true: objects that are not equal() do not have to have different hashcodes, but it is usually better if they do.
    There is quite a lot to know about hashcodes, and what makes a good one, so I suggest you follow dcminter's advice if you want to be a happy and prosperous Java programmer.
    Winston

  • Implementing hashcode and equals

    Is there anything more than performance reasons to always implement hashCode when you implement equals? If I understand correctly, when you put items in a hashtable it chooses the bucket by the hashcode and checks there is no equal item with the equals method. So it should still work if you never implement the hashcode method. But is there any other reason to implement hashCode than performance? Or have I just understood this completely wrong?

    Everything you say is true. And your example shows that point well. However, what if I just implement a hashCode that always returns 0? How will this work then? And does it have any differences than performance?
    Here is an example
    import junit.framework.*;
    import java.util.*;
    public class EqualsTest extends TestCase
      public void testHashCode()
        Map hashTable = new Hashtable();
        hashTable.put( new TestItem( 0 ), "0" );
        hashTable.put( new TestItem( 1 ), "1" );
        assertEquals( 2, hashTable.size() );
        Set hashSet = new HashSet();
        hashSet.add( new TestItem( 0 ));
        hashSet.add( new TestItem( 1 ) );
        assertEquals( 2, hashSet.size() );
      private class TestItem
        private final int i;
        public TestItem( int i )
          this.i = i;
        public boolean equals( Object o )
          final TestItem testItem = ( TestItem ) o;
          return i == testItem.i;
        public int hashCode()
          return 0;
    [/code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for

  • Cannot print to Epson Artisan 725

    Okay, the first time I set this thing up I was able to print wirelessly no problem. After restart, though, it refused to print at all--not via USB, Ethernet or wireless. It does, however, scan and save to my computer just fine. Epson of course feels

  • How can i include css in html file when exported

    I want the CSS should be included in the html file when exported, how is that posable?

  • Silk purses from sow's ears

    When I first bought my eMac, I thought, finally I'll be able to make my little amateur films, and even be a bit ambitious with them. I can make films that don't look like third generation copies of an old VHS video tape which has been copied from VCR

  • How to print a pl/sql raw or BLOB to html page with htp.p command

    Hi! I have a jpeg image I retrieved from the OID and it is stored in an DBMS_LDAP.BINVAL_COLLECTION, which is supposed to be similar to a BLOB or PL/SQL raw collection. What I want to do is to print it to my portal page. I have been using htp.p to pr

  • FI display document for F-29

    can any one send me the t-code of display document for F-29 post custom down payment?