现在的位置: 首页 > 综合 > 正文

Overriding toString(), hashCode() and equals() Methods

2014年01月20日 ⁄ 综合 ⁄ 共 5320字 ⁄ 字号 评论关闭

Overriding toString(), hashCode() and equals() Methods

Overridde toString() when you want to be able to read something meaningful about the objects of your class. Code can call toString() on your object when it wants to read useful details about your object. When you pass an object reference to the System.out.println()
method, the object’s toString() method is called by the JVM, and the output of toString() is printed in the console.

 

toStringDemo t = new toStringDemo();

      System.out.println(t);

      System.out.println(t.toString());

Output:

corejava.toStringDemo@a90653

corejava.toStringDemo@a90653

The preceding output is what you get when you don’t override the toString() method of class Object. It gives you the class name followed by the @symbol, followed by the unsigned hexadecimal representation of the object’s hashCode.

 

Override toString() method in class,

publicclass toStringDemo {

    publicstaticvoid main(String args[]){

      childClass t = new childClass(19,"abc");

      System.out.println(t);

      System.out.println(t.toString());

    }

}

@Override

class childClass{

      privateintage;

      private String
name;

      childClass(int age, String name){

            this.age=age;

            this.name=name;

      }

      public String toString(){

            return"I'm the "+name+"
about "
+age+" years old.";

      }

}

Output:

I'm the abc about 19 years old.

I'm the abc about 19 years old.

 

The toString() method is extremely useful and probably you guessed why you need it in your code. Yes, you are right, it is to help others and probably even you when you run your program at a later point in time to display the details
of your object. Unless, you are ok with the ClassName@HashCode output we just saw a few lines ago.

 

Overriding equals() Method

We used to equals() method on Wrappers. We know how comparing two object references using the == operator evaluates to true only when both references refer to the same object(because==simple looks at the bits in the variable, and they’re either identical
or they’re not). You saw that the String class and the wrapper classes have overridden the equals() method, so that you could compare two different objects to see if their contents are meaningfully equivalent. If two different Interger instances both hold
the int value 5, as far as you’re concerned they are equal. The fact that the value 5 lives in two separate objects doesn’t matter.

When you really need to know if two references are identical, use ==. But when you need to know if the objects themselves are equal(the contents of the object), use the equals() method. For each class you write, you must decide if it makes sence to consider
two different instances equal. For some classes, you might decide that two objects can never be equal. For example, imagine a class Car that has instance variables for things like make, model, year, configuration-you certainly don’t want your neighbor driving
off in it just because he has a same car. So no two cars should ever be considered exactly equal.

There’s a limitation here: if you don’t override a class’s equals() method, you won’t be able to use those objects as a key in a hashtable and you probably won’t get accurate Sets, such that there are no conceptual duplicates.

The equals() method in class Object uses only the == operator for comparisons, so unless you override equals(), two objects are considered equal only if the two references refer to the same object.

@Override

      publicboolean equals(Object obj){

            if(obj
instanceof childClass){

                  childClass t = (childClass) obj;

                  if(t.name==this.name){

                        returntrue;

                  }

            }else{

                  returnfalse;

            }

            returnfalse;

      }

 

Overrides hashCode() method

hashCodes are typically used to increase the performance of large collections of data. The hashCode value of an object is used by some collection classes. Although you can think of it as kind of an object ID number, it isn’t necessarily unique. Collections
such as HashMap and HashSet use the hashCode value of an object to determine how the object should be stored in the collection, and the hashCode is used again to help locate the object in the collection.

Let’s look at an example:

Key

Hash Code Algorithm

Hash Code

Rocky

R(18) + o(15) + c(3) + k(11) + y(25)

72

Anand

A(1) + n(14) + a(1) + n(14) + d(4)

34

The above is a simple algorithm that just sums up the numeric position of the alphabets in the name and arrives at a number that being 72 for Rocky and 34 for Anand. So in the hashCode bucket, the value 34 will be saved as the key for Anand and similarly
72 will be the value of Rocky.

You can see why if two objects are considered equal, their hashcodes must also be equal? Otherwise, you’d never be able to fund the object since the default hashCode method in class Object virtually always comes up with a unique number for each object, even
if the equals() method is overridden in such a way that two or more objects are considered equal. It doesn’t matter how equal the objects are if their hashcodes don’t reflect that. So one more time: If two objects are equal, their hashcodes must be equals
as well.

@Override

      publicint hashCode(){

            returnage*17;

      }

From the Java API documentation for class Object, the hashCode() contract is as follows:

(1). 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. This
integer need not remain consistent from one execution of an application to another execution of the same application.

(2). If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.

(3). If 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.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

抱歉!评论已关闭.