Subclass overrides the toString, equals, hashCode methods in the Object class

Object is also called super class, it is the ancestor of all classes, all classes inherit methods such as toString, equals, hashCode.
Most of the inherited methods need to be rewritten and improved before they can be put into practical applications.

When outputting an object, the default output content is: class name + "@" + hashCode value.

输的内容:com.ives.fourteen.Student@745f

The output is too abstract to see valuable information.

Override toString

public String toString() {
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }
输出的内容:Student{
    
    name='tom', sex='man', age=18}

When outputting an object, you can see the attributes and corresponding values ​​of the object

equals

When comparing two objects, equals compares the memory addresses of the two objects by default.

If the IDs of variable A and variable B are equal, for us humans, they should be equal, but from the machine's point of view, the memory addresses of A and B are not equal, so they are not equal.
So we need to rewrite equals in line with the rules of real life.

    public boolean equals(Object o) {
    
    
        //如果两个对象内存地址相同,那么返回true
        if (this == o) return true;
        //如果比较的对象为null、或者两个对象的类不一样,那么返回false
        if (o == null || getClass() != o.getClass()) return false;
        //强制类型转换
        Student student = (Student) o;
        //比较两个对象的ID,如果ID相等,就代表两个对象相等。(ID是唯一的)
        return ID == student.ID;
    }

hashCode

In a Java collection, the process of judging whether two objects are equal is as follows:

  1. Compare the hashCode of two objects
  2. Two objects are equals

For example, if there are two objects with the same ID and different hashCodes are assigned, the machine will think that they are two different objects in the collection.
So we need to rewrite hashCode in line with real life rules.

    public int hashCode() {
    
    
    	//根据ID分配hashCode值
        return Objects.hash(ID);
    }

Guess you like

Origin blog.csdn.net/Mr_Qian_Ives/article/details/110424332
Recommended