java中==和equals和hashCode的区别

"=="、equals、hashCode的含义

  • "==":在Java中,"=="是一种运算符,用来表示两个变量是否相等。
int a = 12;
int b = 10;
boolean boo = a == b;
  • equals是Object类的一个方法,用于比较两个对象是否相等,默认比较的是两个对象的地址值。
 public boolean equals(Object obj) {
        return (this == obj);
 }
  • hashCode也是Object类的一个方法,返回一个离散的int型整数,hashCode通过计算返回两个hash值,这个值可能是相同的可能是不同的,所以拿hashCode的值进行比较是不安全、不可靠的。
System.out.println("1".hashCode());  // 结果是一个hash值,49

"=="与equals的对比

  • "=="比较的是地址值,equals如果没有重写的话也是拿两个对象的地址值进行比较的。
  • 我们在日常开发中经常拿equals对String字符串进行比对,拿到最终的Boolean类型值进行判断,但是我们通常用到的equals都是通过String类重写过的。
 public boolean equals(Object anObject) {
        // 首先比较两个值得地址值是否一样
        if (this == anObject) {
            return true;
        }
        // 判断该值是否是String类的一个实例
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = value.length;
            // 比较两个字符串长度是否相等
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    // 逐一比较两个字符是否相等,并最终确定两个值是否相等
                    if (v1[i] != v2[i])
                        return false;
                    i++;
                }
                return true;
            }
        }
        return false;
 }
  • 所以得出结论,Object下的equals作用和"=="相同,String下的equals作用和"=="不同。

equals与hashCode的关系

Java对于两者有这样的约束

  • 如果两个值equals,他们的hashCode就一定相同。
  • 如果两个值不equals,他们的hashCode可能相同,可能不同。
  • 如果两个值的hashCode相同,他们不一定equals。
  • 如果两个值的hashCode不同,他们一定不equals。
  • 同一个对象多次调用hashCode(),返回的值总是相等的。
  • 特别注意如果我们重写了equals,必须要重写hashCode,否则会为代码埋下bug,从而导致该类无法结合所有基于散列的集合一起正常运作,这样的集合包括HashMap、HashSet和Hashtable。

如何重写equals与hashCode

  • 先来看一段只重写equals而不重写hashCode的代码,看看会出现怎样的问题。

bean类:重写了equals,判断只当name相同就equals。

public class Student {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public boolean equals(Object o) {
        if (name == null || o == null) {
            return false;
        }
        if (o instanceof Student) {
            Student student = (Student) o;
            // 名字相同就equals
            return name.equals(student.name);
        }
        return false;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Test类

public class Test {
    public static void main(String[] args) {
        Student student1 = new Student("hulk", 12);
        Student student2 = new Student("hulk", 13);

        System.out.println(student1.equals(student2));  // 输出结果:true
        System.out.println(student1.hashCode());        // 输出结果:1627674070
        System.out.println(student2.hashCode());        // 输出结果:1360875712

        Set<Student> set = new HashSet<>();
        set.add(student1);
        set.add(student2);
        // 输出结果:[Student{name='hulk', age=12}, Student{name='hulk', age=13}]
        System.out.println(set);
    }
}

可以看到当两个对象equals时,他们的hashCode仍然不同,这明显不符合Java约束,而且导致了在HashSet中存储了两份。

  • 把重写的hashCode加入之后看看会是怎样的结果。
  @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + (name == null ? 0 : name.hashCode());
        return result;
    }
public class Test {
    public static void main(String[] args) {
        Student student1 = new Student("hulk", 12);
        Student student2 = new Student("hulk", 13);

        System.out.println(student1.equals(student2));  // 输出结果:true
        System.out.println(student1.hashCode());        // 输出结果:3214683
        System.out.println(student2.hashCode());        // 输出结果:3214683

        Set<Student> set = new HashSet<>();
        set.add(student1);
        set.add(student2);
        // 输出结果:[Student{name='hulk', age=12}]
        System.out.println(set);
    }
}

此时hashCode的值相等了,而且hashSet里也只有了一个hulk(学生的名字)。


一些关于"=="的面试题

public class exercises {
    public static void main(String[] args) {
        int int1 = 12;
        int int2 = 12;
        Integer Integer1 = new Integer(12);
        Integer Integer2 = new Integer(12);
        Integer Integer3 = new Integer(127);

        Integer a7 = 127;
        Integer b7 = 127;

        Integer a8 = 128;
        Integer b8 = 128;

        String s1 = "str";
        String s2 = "str";
        String str1 = new String("str");
        String str2 = new String("str");

        // int1 == int2 true,"=="是比较变量是否相等的
        System.out.println(int1 == int2);
        // int1 == Integer2 true,Integer会自动拆箱为int,然后再比对
        System.out.println(int1 == Integer2);
        // Integer1 == Integer2 false,两者地址值不同
        System.out.println(Integer1 == Integer2);
        // Integer3 == a7 false,Integer3是new出来的,a7指向的是缓存中的127,地址值不同
        System.out.println(Integer3 == a7);
        // a7 == b7 true,都指向缓存中的127
        System.out.println(a7 == b7);
        // a8 == b8 false,缓存大小为[-128,127]
        System.out.println(a8 == b8);
        // s1 == s2 true,s1先在缓存中创建"str",之后s2也指向了这个值
        System.out.println(s1 == s2);
        // str1 == str2 false,new出来的都是一个新的地址值,所以地址值不同
        System.out.println(str1 == str2);
        // s1 == str1 false,地址值不同
        System.out.println(s1 == str1);
    }
}
Integer a7  = 127;
java在编译的时候,被翻译成-> Integer a7 = Integer.valueOf(127);
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。