==和equals()

1、==:基本数据类型(int a = 1; String s = “hello”;)比较的是值,引用数据类型(Integer c = new Integer(2); String str = new String(“world”);)比较的是内存地址

2、equals():

情况1:类没有覆盖equals()方法。等价于通过“==”比较这两个对象,也就是比较地址

情况2:类覆盖了equals()方法。一般,都(String类,Integer类等)覆盖equals()方法来比较两个对象的值

public class Hello {

    public static void main(String[] args) {
        //基本数据类型
        int a1 = 1;
        int a2 = 1;
        System.out.println(a1 == a2); //true

        String s1 = "hello";
        String s2 = "hello";
        System.out.println(s1 == s2);   //true

        //引用数据类型
        Integer a3 = new Integer(2);
        Integer a4 = new Integer(2);
        System.out.println(a3 == a4);   //false
        System.out.println(a3.equals(a4));  //true

        String s3 = new String("world");
        String s4 = new String("world");
        System.out.println(s3 == s4);   //false
        System.out.println(s3.equals(s4));  //true

        User user1 = new User("y0", 20);
        User user2 = new User("y0", 20);
        System.out.println(user1 == user2); //false
        System.out.println(user1.equals(user2));    //User类没有覆盖equals()方法时为false,User类覆盖了equals()方法时为true
    }

}

重写equals()方法时必须重写hashCode()方法 

hashCode()的作用是获取哈希码,也称为散列码;它实际上是返回一个int整数。这个哈希码的作用是确定该对象在哈希表中的索引位置。哈希表存储的是键值对,它的特点是能根据键快速的检索出对应的值,这其中就利用到了散列码。

public class Hello {

    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1.hashCode());  //99162322
        System.out.println(s2.hashCode());  //99162322

        User user1 = new User("y1", 21);
        User user2 = new User("y1", 21);
        System.out.println(user1.hashCode());
        System.out.println(user2.hashCode());   //User类重写了hashCode()方法时,哈希码是一致的,否则是不一致的
    }
}

如果两个对象的equals()方法相等并且对象类重写了hashCode()方法时,哈希码才是一致的。

原文地址:https://www.cnblogs.com/yanguobin/p/11603709.html