[equals method] related issues

1. What is the difference between == and equals?

==:
For basic data types, == compares values.
For reference data types, == compares the memory address of the object.

Because Java only transfers by value, for ==, whether it is comparing basic data types or variables of reference data types, the essence of comparison is the value, but the value stored in the reference type variable is the address of the object.

equals:
The function of equals() cannot be used to judge variables of basic data types, but can only be used to judge whether two objects are equal. The equals() method exists in the Object class which is the direct or indirect parent class of all classes.
The class does not override the equals() method: when comparing two objects of this class through equals(), it is equivalent to comparing the two objects through "==", and the default is the equals() method of the Object class.
The class overrides the equals() method: Generally, we override the equals() method to compare whether the properties in two objects are equal; if their properties are equal, return true (that is, the two objects are considered equal).

public class test1 {
    
    
    public static void main(String[] args) {
    
    
        String a = new String("ab"); // a 为一个引用
        String b = new String("ab"); // b为另一个引用,对象的内容一样
        String aa = "ab"; // 放在常量池中
        String bb = "ab"; // 从常量池中查找
        if (aa == bb) // true
            System.out.println("aa==bb");
        if (a == b) // false,非同一对象
            System.out.println("a==b");
        if (a.equals(b)) // true
            System.out.println("aEQb");
        if (42 == 42.0) {
    
     // true
            System.out.println("true");
        }
    }
}

The equals method in String is overridden, because the equals method of Object is to compare the memory address of the object, and the equals method of String is to compare the value of the object.

When creating an object of type String, the virtual machine will look in the constant pool to see if there is an object with the same value as the one to be created, and if so, assign it to the current reference. If not, recreate a String object in the constant pool.

== For basic types, it is a value comparison, for reference types, it is a reference comparison; and equals is a reference comparison by default, but many classes rewrite the equals method, such as String, Integer, etc. to change it to Value comparison, so in general, equals compares whether the values ​​are equal.

2. hashCode() and equals()

1. The function of hashCode():

What hashCode() does is get the hash code, also known as the hash code; it actually returns an int. The function of this hash code is to determine the index position of the object in the hash table. hashCode() is defined in the Object class of JDK, which means that any class in Java contains the hashCode() function. In addition, it should be noted that: the hashcode method of Object is a local method, which is implemented in c language or c++. This method is usually used to convert the memory address of the object into an integer and then return it.

public native int hashCode();

The hash table stores key-value pairs (key-value), and its characteristic is that it can quickly retrieve the corresponding "value" according to the "key". This is where hash codes are used! (you can quickly find the desired object)

2. Why is there a hashCode?

When you add an object to HashSet, HashSet will first calculate the hashcode value of the object to determine the location where the object is added, and also compare it with the hashcode values ​​of other objects that have been added. If there is no matching hashcode, HashSet will assume that the object is not duplicated Appear. But if an object with the same hashcode value is found, the equals() method will be called to check whether the objects with the same hashcode are really the same. If the two are the same, the HashSet will not let its join operation succeed. If it is different, it will be rehashed to another location. In this way, we greatly reduce the number of equals, which greatly improves the execution speed.

3. Why must the hashCode method be rewritten when rewriting equals?

If two objects are equal, the hashcode must also be the same. Two objects are equal, calling the equals method on the two objects returns true. However, two objects with the same hashcode value are not necessarily equal. Therefore, if the equals method is overridden, the hashCode method must also be overridden.

The default behavior of hashCode() is to generate unique values ​​for objects on the heap. If hashCode() is not overridden, no two objects of this class will be equal anyway (even if the two objects point to the same data)

4. Why two objects have the same hashCode value, but they are not necessarily equal?

The hashCode() of "call" and "heavy ground" are the same, but equals() is false, because in the hash table, hashCode() is equal, that is, the hash values ​​​​of the two key-value pairs are equal, but the hash values ​​​​are equal, and It is not necessarily possible to conclude that key-value pairs are equal.

Because the hash algorithm used by hashCode() may just cause multiple objects to return the same hash value. The worse the hash algorithm is, the easier it is to collide, but this is also related to the characteristics of the data value field distribution (the so-called collision means that different objects get the same hashCode.

We also mentioned HashSet just now. If HashSet has multiple objects with the same hashcode during comparison, it will use equals() to determine whether they are really the same. That is to say, hashcode is only used to reduce the search cost.

3. A null pointer appears when using the equals() method

When using equals(), a null pointer exception is reported because the method is called with a null value. Remember that null cannot call a method. When using equals, we must first verify the validity of the value. Or use a constant to call the equals() method!

EX:

public static void main(String[] args) {
    
    
    User user = new User();
    user.setName("王二");

    User user2 = new User();
    user2.setAge(18);

    if (user.getName().equals(user2.getName())){
    
     //user.getName()不是null,则不会报空指针异常
        System.out.println("是王二");
    }
    
    if("王二".equals(user.getName())){
    
     //使用常量去调用equals()方法,也不会报空指针异常
        System.out.println("是王二");
    }
}

4. Usage of equals() and indexof(), contains()

equals(): Determine whether two strings are equal;
IndexOf() and Contains(): Determine whether the specified string is contained in the string, and both IndexOf() and Contains() are case-sensitive

1. The IndexOf() and Contains() methods are not case-sensitive:

The IndexOf() method has a built-in parameter StringComparison.OrdinalIgnoreCase that can be set to be case-insensitive

string str1="Abc";  string str2="abc";
str1.IndexOf(str2,StringComparison.OrdinalIgnoreCase);

The Contains() method can only convert the string to uppercase or lowercase first to achieve case insensitivity

string str1="Abc";  string str2="abc";
str1.ToUpper().Contains(str2.ToUpper());

2. Matching efficiency:

In the case of case sensitivity, the Contains() method will be more efficient than the IndexOf() method
In the case of case insensitivity, the IndexOf() method will be more efficient than the Contains() method

3. Return value type:

The IndexOf() method returns the first subscript that contains the specified string, the subscript starts from 0, and returns -1 if it is not included.
The Contains() method returns true if it contains the specified string, and false if it does not.

Guess you like

Origin blog.csdn.net/m0_46459413/article/details/131324096