==与.equals()的区别
- 比较内存地址是否相同:.equals(Object o)与==一致,如果引用同一对象,则结果都为true;
举例说明:
boolean isSame=false;
Customer c1=new Customer();
Customer c2=c1;
isSame=(c1==c2); 说明:isSame=true;
isSame=(c1.equals(c2)) 说明:isSame=true;
- 比较值是否相同:在Java中,因为以下类覆盖了Object类的.equals(Object o)的方法,实现了按值比较,这些类包括:
- String类和Date类
- Java包装类,如:Byte,Integer,Short,Character,Long,Float,Double,Boolean
所以在以上类中,引用对象的不同使==返回值为false,而值相同的引用对象.equals(Object o)方法返 回值为true;
举例说明:
boolean isSame=false;
String s1=new String("Hello");
String s2=new String("Hello");
isSame=(s1==s2); 说明:isSame=false;
isSame=(s1.equals(s2)); 说明:isSame=true;
============================================================================================
附:如何在自定义类Customer中覆盖Object类中的.equals(Object o)方法,使其可以按值比较,
public boolean equals(Object o){
if(this==o) return true;
if(!o instanceof Customer) return false;
final Customer other=(Customer)o;
if(this.getName().equals(other.getName())) return true;
else return false;
}