A classic Java interview question: the difference between equals, == and hashcode()

==

Value comparisons are used for primitive types, and reference comparisons are used for reference types.

	/**
     * == 的比较
     */
    @Test
    public void testOne(){
        int a = 200;
        int b = 200;
        Integer c = 200;
        Integer d = 200;
        //值比较
        System.out.println(a == b);//同基本类型同值比较:true
        //引用类型比较
        System.out.println(c == d);//false
    }

equals

equals is the method of the original class Object, that is, all objects have the equals method. By default (that is, not overridden), it is a reference comparison, but many classes in the JDK have rewritten the equals method (usually, == is compared first, and then judged). Whether to perform value comparison), so in general, it is value comparison. Note: Basic types cannot use equals comparison, but use ==, because basic types do not have an equals method.

Let's take a look at the equals method overridden by Obeject:

//Object:
public boolean equals(Object obj) {
        return (this == obj);
    }
    
 //Integer :
 //先判断是否为同一类型,不是直接false,是的话在进行值比较
public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
    
//String:
//先比较地址,然后判断是否为同一类型,不是直接false,是的话在进行值比较
public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        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;
    }

Comparison of equals

class Cat{
    String name = "cat";
}
class Dog{
    String name = "dog";
}
________________________________________________________________________
	/**
     * euqals 比较
     */
    @Test
    public void testTwo(){
        int a = 200;
        int b = 200;
        Integer c = 300;
        Integer d = 300;
        Cat cat = new Cat();
        Dog dog = new Dog();
        System.out.println(c.equals(a));//false
        System.out.println(c.equals(d));//true
        //System.out.println(a.equals(cat));//基本类型不能使用equals比较,而是用==,因为基本类型没有equals方法
    }

hashcode()

Hashcode() is also a method of Object. It is a native method, implemented in C/C++ language, and the address value of the returned object is called by java. But many classes in the JDK rewrite hashcode(). For example, if Boolean means true, the hash value is 1231, and if it means false, the hash value is 1237.

	//Object:
	public native int hashCode();
	
	//Integer直接返回值
    public int hashCode() {
        return Integer.hashCode(value);
    }
    public static int hashCode(int value) {
        return value;
    }
    
	//String 返回此字符串的哈希码。
	public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

Simple use of hashcode() :

class Cat{
    String name = "cat";
}
class Dog{
    String name = "dog";
}
---------------------------------------------------------------------
	@Test
    public void testThree(){
        Cat cat = new Cat();
        Dog dog = new Dog();
        System.out.println(cat.hashCode());//204349222
        System.out.println(dog.hashCode());//231685785
        Integer a = 200;
        Integer b = 300;
        System.out.println(a.hashCode());//200
        System.out.println(b.hashCode());//300
    }

Comparison of equals and ==, hashcode() :

  1. Two objects that are equal() are equal and their hashCode() must be equal.
  2. Two objects with equal hashCode() are not necessarily equal to their equal().

Try using associations to remember the above concepts. For example, the HashMap we use. Its structure is as follows:

If the hashcode() is equal, then they have the same bucket position . At this time, it is like Entry1 and Entry2. However, the equals of Entry1 and Entry2 do not necessarily want to wait. This is another example. Entry1=abc, Entry2=abc, then They are equal, but Entry1=abc, Entry2=def, then they are not equal. equals are equal, then they are on the same column , which means that the position of the bucket is the same, then .hashCode() must be the same

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324072262&siteId=291194637