==:比较的都是栈内存中的值,比如,int a=4,b=5; 那么a==b比较的就是4==5
而对于引用数据类型,比如,字符串Strng str1="abc", str2=="bcd"; str1中是栈内存中的变量,它不是直接存储的"abc",它存的是地址值"abc"在堆内存的地址值,比方说这个地址值是0x123,str2同理,比方说它的地址值是0x124,那么str1==str2,比较的就是0x123==0x124,而不比较的"abc"跟"bcd"里面的字符
equals():是类中的方法,比如上例中str1.equals(str2),这里比较的是堆内存中想对应的"abc"跟"bcd";这是java定义好的,你只要知道它比较什么,拿来用就好了。但对于自定义的类,你可以通过覆盖它从父类继承的equals(),来自定义自己想比较的内容,比如
- class Person{
- String name;
- int age;
- Person(){}
- Person(String name,int age){
- this.name=name;
- this.age=age;
- }
- public boolean equals(Object obj){
-
- Person p = (Person)obj;
-
- return this.age==p.age;//父类equal()比较age
-
- }
- }
- class Student extends Person{
- Student(){
-
- }
- Student(String name,int age){
- super(name,age);
- }
- public boolean equals(Object obj){
-
- Student st = (Student)obj;
-
- return this.name.equals(st.name);//父类equal()比较String类name在堆内存中的值
-
- }
- }
- public class EqualsTest {
- public static void main(String[] args) {
- System.out.println("父类equals()比较age");
- Person p1=new Person("zhangsan",19);
- Person p2=new Person("zhangsan",18);
- Person p3=new Person("wangwu",19);
-
- System.out.println(p1.equals(p2));//父类比较age,此处为false
- System.out.println(p1.equals(p3));//父类比较age,此处为true
-
- System.out.println("子类equals()比较name");
- Student st1=new Student("zhangsan",19);
- Student st2=new Student("zhangsan",18);
- Student st3=new Student("wangwu",19);
-
- System.out.println(st1.equals(st2));//子类比较age,此处为true
- System.out.println(st1.equals(st3));//子类比较age,此处为false
-
- }
- }
复制代码
|