Overriding toString(), hashCode() and equals() Methods
来源:互联网 发布:淘宝小白是什么意思啊 编辑:程序博客网 时间:2024/06/06 09:18
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 Stringname;
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(objinstanceof 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.
- Overriding toString(), hashCode() and equals() Methods
- override equals() and hashCode() methods
- Container Class and its equals(), hashCode() methods
- Overriding and Hiding Methods
- Overriding and Hiding Methods
- Working with hashCode and equals methods in java
- Working with hashCode and equals methods in java
- equals, hashCode,toString
- equals() 、 toString() 、 getClass() 、 hashCode()
- equals&&hashCode&&toString函数
- equals()、hashCode()、toString()
- equals hashcode toString
- Why always override hashcode() if overriding equals()?
- Java:Java中Overriding and Hiding Methods
- Object 类 equals toString hashCode
- equals、hashCode、toString 方法重写
- C# : Enum and overriding ToString on it
- hashCode() and equals()
- GCC/LD编译链接潜规则 (第四弹) : ld 会把所有通过-l指定的动态库全部链接进最终的目标程序中, 无论是否真的用到(导致生产环境加载失败)
- android OTA 的功能实现和修改
- Android网络编程之Socket&Http
- CentOS 6.3下Samba服务器的安装与配置
- c# 控制IE浏览器
- Overriding toString(), hashCode() and equals() Methods
- java中String的常用方法
- 手机交互设计原则
- Linux 之 shell 比较运算符
- 用java实现打印功能
- (一)计算机网络课程设计教学大纲
- GCC/LD编译链接潜规则 (第五弹) : 为什么会有undified symbol?
- 二叉查找树的各种操作源码
- android4.2.2 飞思卡尔 编译错误笔记 ubuntu12.04