1、==如果作用于基本数据类型,则比较的是值是否相等;

   如果作用于引用类型,则比较的是变量所指向的对象的地址

2、对于非String、Date类型equals比较的是引用类型的变量所指向的对象的地址

  但对于String、Date类型,在其类中重写了equals(),所以比较的是值

3、Object类型相等判断为什么重写equals()和hashcode()

  equals()方法是比较两个对象的内存地址是否相等,如果不重写,显然两个对象由于不同存储地址所以是不相等的  

package nio;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ListTest {

    public static void main(String[] args) {
        Person p1 = new Person(10, "张三");
        Person p2 = new Person(10, "张三");
        System.out.println(p1.equals(p2));
        System.out.println(p1.hashCode()==p2.hashCode());
        
    }
    
}

class Person {
    int age;
    String name;

    public Person(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {  //重写equals方法
        boolean flag=false;
        if(this==obj) {
            flag=true;
        }
        if(null != obj) {
            Person other=(Person) obj;   //对象转化为person类型对象
            if((age==other.age) && (name==other.name)){
                flag=true;
            }
        }
        
        return flag;
    }

    @Override
    public int hashCode() {
        final int prime=31;
        int result=1;
        result=prime*result+age;
        result=prime*result+((name==null)?0:name.hashCode());
        return result;
    }
}

如果不重写equals方法则 System.out.println(p1.equals(p2))返回false
如果不重写hashcode方法则System.out.println(p1.hashCode()==p2.hashCode())返回false
View Code

 

 

4、重写equals()为什么一定要重写hashcode()

  如果两个对象判断相等只重写了euqals()方法,而没有重写hashcode()方法,虽然p1.equals(p2)结果是true,但执行p1.hashCode()==p2.hashCode()结果却是false,这与“两个对象相等,其hashcode必然相等”矛盾,所以重写了equals()必然需要重写hashcode()

  hashcode()判断是equals()判断的先决条件,所以对象重写了equals()需要重写hashcode()

posted on 2019-06-11 22:05  colorfulworld  阅读(3056)  评论(0编辑  收藏  举报