Judging whether two objects are equal in Java

Posted by porto88 on Sun, 14 Jul 2019 21:07:04 +0200

There are many ways to determine whether two objects are equal in Java, which will be explained briefly here.

  1. For basic data types, we can directly use "==" to judge, equality returns true, and vice versa, false.

  2. Comparisons with Reference Types
    Suppose that there are two reference objects obj1,obj2, obj1==obj2 to determine whether the two reference variables obj1 and obj2 are equal, that is, whether the object they refer to is the same object. The implication is that only when the memory addresses of the two variables are equal can true be returned. Each object has its own piece of memory, so it must point to the same object to return true. The default equal() in object is also a reference variable.

    public boolean equals(Object obj) {
        return (this == obj);
    }

    3. After Java provides basic types, in order to maintain the requirement of strong objects, it also introduces their wrapper classes, which rewrite some methods to produce some interesting results.
    1).
    It's also initialization, and different ways have different effects.

 Integer a = 10; Integer b = 10;
 System.out.println(a == b);//true 
 Integer a = 200; Integer b = 200;
 System.out.println(a == b);//false 
 Integer a = 10; Integer b = new Integer(10);
 System.out.println(a == b);//false

Here's the Integer part of the JDK source code

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];
        static {
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);  
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {                   
                }
            }
            high = h;
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);           
            assert IntegerCache.high >= 127;
        }
        private IntegerCache() {}
    }

From the above examples and source code, we can know that:
When Integer is initialized as a wrapper class, if the parameter is within [-127,128], it will automatically call an object in the cache array.
At this point, because the parameters are not in this range, a new object is needed. The two objects are different and the reference is false.

2. When using equal to compare

System.out.println(new Integer(1).equals(1)); // true
System.out.println(((Long)1L) == 1); // true
System.out.println(new Long(1).equals(1)); // false
System.out.println(new Long(1).equals(1L));//true

JDK source code:

Integer
public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}
Long
  public boolean equals(Object obj) {
    if (obj instanceof Long) {
        return value == ((Long)obj).longValue();
    }
    return false;
}

From the above examples and source code, we can know that:
The equals parameter accepts an Object object, so 1 is automatically boxed into Integer.valueOf(1). Let's look at Long's equals implementation. If the incoming type is Long, then compare the values. If the incoming type is other, return false directly.

3).
When using hashcode(), wrapper classes such as Interger generate hash codes based on the values contained in the class. That is, two integer values of the same size are equal in hashCode.

The hashCode in Object class is different from the previous one. It is the hashCode obtained by hashing algorithm according to the memory address of the object. Because the memory address of each object is different, the hashCode is different.

So when we use hash codes to compare, we should remember that if hash codes are different, the objects must be different. When hash codes are the same, the objects are not necessarily equal.

Topics: Java JDK