1.equals();对于基本类型数据比较的是数值,对于对象类型的数据则是比较引用,既是两个对象是否指向了同一块存储区域;
2.hashCode();返回一个散列码,是否对象导出的导出的整数值,如果x,y是两个不同的对象,那么x.hashode()和 y.hashCode一般不会相同;
注意:如果子类中重写了equals方法就一定要重新定义hashCode方法。
3.toString();返回便是对象值的字符串,只要对象与一个字符串通过操作符“+”连接起来,java编译就会自动调用toString()方法,以便获得这个对象的字符串描述。,强烈建议为自定义的每一个类增加toString方法。
以下是代码示例:
package TestEquals;
import com.google.common.base.Objects;
public class testEquals {
private String foo;
private int num;
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
/**
* 重写equals方法
*/
@Override
public boolean equals(Object otherObject) {
if (this == otherObject)
return true;
if (otherObject == null)
return false;
if (getClass() != otherObject.getClass())
return false;
testEquals othertestequals = (testEquals) otherObject;
return Objects.equal(foo, othertestequals.foo) // String的值可以用equal比对
&& num == othertestequals.num; // int类型的数值用 == 比对
}
/**
* 重写hashCode方法
*
*/
@Override
public int hashCode() {
return foo.hashCode() + new Integer(num).hashCode();
}
public static void main(String[] args) {
testEquals t1 = new testEquals();
testEquals t2 = new testEquals();
t1.setFoo("123");
t1.setNum(1);
t2.setFoo("123");
t2.setNum(1);
System.out.println(t1.equals(t2) + "12312");
}
/**
* 重写toString()方法
*/
@Override
public String toString() {
return "testEquals [foo=" + foo + ", num=" + num + "]";
}
}
package TestEquals;
import com.google.common.base.Objects;
public class testExtendsEquals extends testEquals {
private String addr;
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
/**
* 重写子类的equals
*/
@Override
public boolean equals(Object otherObject) {
if (!super.equals(otherObject))
return false;
testExtendsEquals othertestextendsquals = (testExtendsEquals) otherObject;
return Objects.equal(addr, othertestextendsquals.addr);
}
/**
* 重写子类的hashCode方法
*
*/
@Override
public int hashCode() {
return super.hashCode() + addr.hashCode();
}
/**
* 重写子类的toString()方法
*/
public String toString() {
return super.toString() + "[addr=" + addr + "]";
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
testExtendsEquals tt1 = new testExtendsEquals();
testExtendsEquals tt2 = new testExtendsEquals();
tt1.setAddr("234");
tt1.setFoo("234");
tt1.setNum(2);
tt2.setAddr("234");
tt2.setFoo("234");
tt2.setNum(2);
System.out.println(tt1.equals(tt2) + "234");
}
}