equals和==
equals方法
equals方法是在Object类中定义的,它是提供对象是否”相同“的逻辑,如:x.equals(y),return (this == obj);
如果x和y是同一个对象的引用返回True否则返回false。所以它的作用与==
没有什么区别都是比较内存地址。所以你想用equals比较两个对象的内容的值相同是不行的,而一般的类都是间接或直接基础了Object类,如果不进行重写equals方法是无法比较内容是否相同的。如:String、Date等,就进行了重写equals
对于String类中的equals方法
String类中重写了equals方法用来比较两个字符串的内容是否相同
对于==
在String中是比较引用内存地址是否相同,如下s1==s2
为什么为true,因为s1和s2是直接创建的它们放在公共池中引用是相同的,所以为true。而s4==s5
String s1="zll";
String s2="zll";
String s4=new String("123");
String s5=new String ("123");
System.out.println(s1.equals(s2));//true
System.out.println(s1 == s2);//true
System.out.println(s4.equals(s5));//true
System.out.println(s4 == s5);//false
对于引用类型数组中equals方法
它没有进行重写equals方法,所以是无法使用equals来比较内容的。比较的还是地址值
int[] arr={1,2};
int[] arr2={1,2};
System.out.println(arr.equals(arr2));//false
对于自己创建的对象中的equals方法
它也是没有进行重写equals方法的,也无法比较两个对象的内容是否相同
package com.zll;
?
public class Demo {
public static void main(String[] args) {
TestDemo t1=new TestDemo("张三",10);
TestDemo t2=new TestDemo("张三",10);
System.out.println(t1.equals(t2));//我自己重写了equals方法返回true,如果没有重写equals方法返回为false,
}
}
class TestDemo{
String name;
int age;
public TestDemo(String name,int age){
this.name=name;
this.age=age;
}
public boolean equals(Object obj){
if(obj==null){
return false;
}
//如果调用该方法的对象和传入的对象是同一个,则直接返回true
if(this==obj){
return true;
}
TestDemo p = (TestDemo) obj;//因为Object类中没有子类Demo的name,age属性,所以要向下转型成Demo类
if(this.name.equals(p.name) && this.age==p.age){//调用的name等于传入的name或者调用的age等于传入的age返回true
return true;
}
return false;
}
}
对于基本数据类型
如果你是基本类型数据(如果是int,double,char..)只能用==