A little question about equals

public class testEquals {
	public static void main(String[] args) {
		Integer i = 1;
		System.out.println("1".equals(i));
		
	}
}

It is taken for granted that "1".equals(i.toString()) i will automatically call the toString() method, by viewing the source code

    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;
    }

Here, we will first judge whether the addresses of the two objects are the same. If the addresses are the same, the objects must be the same. Then we will judge whether they are of the same type. Integer is obviously not a String type, so it will not be equal here! ! !

public class testEquals {
	public static void main(String[] args) {
		Integer i = 1;
		System.out.println("1".equals(i.toString()));//true
		
	}
}
Displays calling toString() to convert i to a string and the result is true


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325963573&siteId=291194637