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.

Similar Messages

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

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

  • 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

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

  • 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();

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

  • SCJP 5.0 A question about hashcode() and equals()

    Here's an exercise from a book.
    Given:
    class SortOf {
    String name;
    int bal;
    String code;
    short rate;
    public int hashCode() {
    return (code.length()*bal);
    public boolean equals(Object o) {
    //insert code here
    Which of the following will fulfill the equals() and hashCode() contracts for this
    class? (Choose all that apply)
    A return ((SortOf)o).bal == this.bal;
    B return ((SortOf)o).code.length() == this.code.length();
    C return ((SortOf)o).code.length()*((SortOf)o).bal == this.code.length()*this.bal;
    D return ((SortOf)o).code.length()*((SortOf)o).bal*((SortOf)o).rate ==
    this.code.length()*this.bal*this.rate;
    C is a correct answer but D is also a correct answer according to the book writer,
    and I don't understand why.
    Normally, the rule is that if two objects are equals (according to the equals
    method)) then they must return the same hashcode. If we have two objects A and B;
    and A.bal == 2, A.code.length()==3, A.rate == 4 and B.bal == 4, B.code.length() ==
    3 and B.rate == 2. A and B are equals according with the D answer but they do not
    return the same hashcode.
    May someone help me make it clear?

    Generally ,the instance members decides the equals( ) & hashCode( ) contract . Here the code.length , bal fields are generating the hashCode.
    So it is appropriate to override the equals( ) method in such a way that , thonly those two fields wil decid the equality of the objects .
    Thanks,
    laksh.

  • 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

  • How to enforce developers to override toString() method

    Hi,
    Right now we are in design stage of our application. I want that all our BO classes should override toString(), equals() and hashCode() methods.
    We expect that our application would be running for next 5 to 10 years, and so looking for ways to enforce these rules to developers.
    One way to do is let ant script handle such validations. Another way could be using PMD to enforce rules.
    These could be good ways of doing this, but my manager doesnot quite like to depend on external tools like these ... as 5 years down the line you donot know state of these tools.
    Can someone suggest if java provides any such provision ...
    If someone has some smart solution do let me know ... your help is much appreciated ... and thanks in advance.
    Regards,
    Rana Biswas

    This is interesting.
    toString() method is already implemented in class Object, which is inherited by all other class.
    What happens if we make toString() method abstract. I tried it and compiler allows to do it ... was wondering if it would have any side effect.
    Regards,
    Rana Biswas

  • Implementation of equals, hashCode, and

    I am writing an RMI application where the implementation of the remote interface cannot extend UnicastRemoteObject because it already extends another class. So, I need to explicitly export the server object using UnicastRemoteObject.exportObject(server, 0);� no problem.
    Problem is I�ve read that in order to make the class behave as if it had extend UnicastRemoteObject, you must provide implementations for equals, hashCode, and toString. I�ve searched the world over for implementations of these methods equivalent to those found in UnicastRemoteObject� no luck so far.
    Could you help me out?
    I�ve found some code that I�ve listed below� Is it equivalent to the equals and hashCode method found in UnicastRemoteObject? What about toString()?
    public class RemoteDataServer extends LocalDataServer implements RemoteInterface{
        private Remote serverStub;
        public RemoteDataServer() throws IOException {
            super();
            //export remote object
            serverStub = UnicastRemoteObject.exportObject(this);
        public boolean equals(Object obj) {
            return (obj == this || serverStub.equals(obj));
        public int hashCode() {
            return serverStub.hashCode();
    //toString()???

    Hi,
    At book Effective Java by Joshua Bloch you can see some info
    overriding these members.
    See at http://java.sun.com/docs/books/effective/index.html
    Here is the toString()spec method from Object :
    Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
    The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
    getClass().getName() + '@' + Integer.toHexString(hashCode())
    but toString from class String simply returns the string contents of
    an object.
    Hope this help

  • Always override: toString(), clone(), equals(Object obj)?

    In classes that I write Is there any reason to not always override:
    public String toString();
    public boolean equals();
    public Object clone(Object obj);Further, why not always provide a default Comparator ?
    public Comparator getDefaultComparator();This seems logical?

    kakusaretasuna wrote:
    thank you.
    I am just beginning to learn Java, and so I am making a checklist of things to do when I write a class.
    When it makes sense, I will always implement:
    toString()
    clone()
    equals()
    getDefaultComparator()getDefaultComparator? No, I wouldn't do that. Where did you get that idea from?
    And if you override equals, you should always override hashCode as well, and vice versa.
    As a rule, I do not override those methods unless I have a specific reason to.
    And, I learned that by default a Java class is not Serializable . Therefore, for each of my
    classes, I need to adjust them to safely be Serializable , and then declare them Serializable Only if there's a reason to serialize them. Again, it doesn't make sense for all classes, or even most.
    This makes sense to me, however, I don't want to appear foolish to exeperienced developers. For example, I learned that:Worry less about appearing foolish and more about learning. Everybody had to start somewhere, and this stuff is generally not intuitive. Nobody cares if you don't automatically know it all.
    >
    private final void foo(); // "final" is annoying and foolish?As with most things, there are at least two schools of thought on that. In general, I don't make methods final unless I specifically don't want them overridden. Some people feel you should declare them final by default, and only remove the final in cases where there are specific reasons to override them. Neither is right or wrong. It's mostly a matter of convention, and somewhat a matter of context.
    private void foo() { this.privateMethod(); } // "this" is annoying and foolish?I personally hate using "this" when it's not necessary, and it's never necessary in the case of method calls. It doesn't even add any clarity. It's just clutter.
    >
    I am sure there are many other construts that experienced developers avoid.Yes, but don't worry about learning them all right now.

  • 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

  • How  to override toString() method ?

    class  Test
    String x[];
    int c;
    Test(int size)
    x=new String[size];
    c=-1;
    public void addString(String str)
    x=new String
    x[++c]=str;
    public void String toString()
    //  i want to override toString method to view the strings existing in the x[]...
    //   how do i view the strings ?
    //  probabily i should NOT use println() here (..as it is inside tostring() method ..right? )
    //   so i should  RETURN   x[] as an array...but the  toString() method return  type is String not the String array!.
    //   so i am in trouble.
    so in a simple way my question is how do i override toString() method to view the Strings stored in the array ?
    i am avoiding println() bcoz of bad design.
    }

    AS you said, the toString method returns a String - this String is supposed to be a representation of the current instance of your class's state. In your case, your class's state is a String array, so you just pick a format for that and make a String that fits that format. Maybe you want it to spit out something like:
    Test[1] = "some string"
    Test[2] = "some other String"If so, code something like:public String toString() {
        StringBuffer returnValue = new StringBuffer();
        for (int i = 0; i < x.length; i++) {
            returnValue.append("Test[" + i + "] = \"" + x[i] + "\"";
        return returnValue.toString();
    } If you don't mind the formatting of the toString method that Lists get, you could just do something like:public String toString() {
        return java.util.Arrays.asList(this).toString();
    } and call it good. That will print out something like:
    [Some String, another String, null]Depending on what's in your array.
    Good Luck
    Lee

  • Overriding toString method of entrySet() in LinkedHashMap

    Hi all,
    I got a LinkedHashMap which return a Set by entrySet() method. When I print the String represantation of the returned Set, I receive something like [key=value, key=value, key= value]. I, however, would like to override toString method so that I can implement my own representation of the Set class which is returned by entrySet() method. How can I do that if it's possible?

    i believe what Peter was saying was to overrider the Set (in your case...the concrete LinkedhashSet class)
    you're not implementing the add, get, contains, etc..function..you're extending it.
    after extending it..you can overide any public and protected method...any other method not overide is still there for you to use.
    so you would have something like this
    public class MyLinkHashSet extends LinkHashSet{
        public String toString(){
             return a String representation you want 
        public Object getMyObject(){ return myObject; }  // your own method
       // you still have all of the other LinkHashSet methods to use
    }

Maybe you are looking for

  • Oracle 10.2 to MS-SQL Server 2005 connectivity

    Hi, I Have oracle10.2 installed on windows server 2003 (server2) and MS SQL server 2005 on windows server 2005(server1). Connectivity architecture 1. I have created the DSN in windows odbc drivers in server2 and tested (connectivity is successful). 2

  • 802.1x on the switch port and Macintosh doesn't work

    * When .1x is turned on for a port where a Mac is connected, after the Mac goes to sleep it doesn't get prompted to authenticate until the link on the port is dropped and reinstated?   The Mac does not continue to have network  access.  * When the sa

  • Dwongrading from OS X 10.3 to OS 8 or 9...?

    I've found three of my CDs: -iMac Software Install -iMac Software Restore -Mac OS9 (says to the side: Mac OS 9.1 Update CD) This old iMac is currently running OS X 10.3, and I'd like to return it to OS 8 or 9, since it's obviously past its prime, and

  • Scrolling too fast with Asus touchpad.

    I have a problem when scrolling down pages using two fingers on my touch pad. I have installed Asus Smart Gestures and enabled "two finger scrolling" and it works fine in every program except Firefox. In Firefox it is being really frustrating, when i

  • Loading module "oracleasm": Unable to load module "oracleasm"

    Hi, I'm trying to install ASM Library RPMs.But the oracleasm configure is failing with the following error: Default user to own the driver interface [507]: Default group to own the driver interface [507]: Start Oracle ASM library driver on boot (y/n)