[JAVA] Identity / equivalence

This is a personal note

Overview

-The same instance is called ** same **, and the same value is called ** equivalent **. -The property that multiple variables refer to the same instance ** Identity ** ・ Identity is judged by ** == operator ** -The instances are different, but they have the same value ** equivalence ** -Use ** equals method ** to determine if the referenced instances have the same value

important point

-The equals method is a method for checking ** equivalence ** defined in ** Object class **. However, the equals method defined in the Object class is implemented to check the identity as follows.

Sample.java


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

-What is the definition of "having the same value" because it depends on each class whether it is a condition that all fields match or it is judged that some fields should also match. It is assumed that the condition is determined and ** equals method is overridden **.

-If the same string literal appears in the code, the reference to the same String instance will be reused. Such a mechanism is called ** constant pool **. So if you use the == operator to determine identity, it will be true.

Sample.java


public class Sample {
	public static void main(String[] args) {
		String a ="sample";
		String b ="sample";
		System.out.println(a==b);//Execution result is true
	}
}

· When you explicitly create a new instance using the ** new operator **, each variable has a different reference In the following code, variable a is assigned a reference to the String instance created in the memory space for the instance, and variable b is assigned a reference to the String instance created in the memory space for the constant by the constant pool. == Operator result returns false

Sample.java


public class Sample {
	public static void main(String[] args) {
		String a=new String("sample");
		String b ="sample";
		System.out.println(a==b);//Execution result is false
	}
}

Recommended Posts

Identity / equivalence
[Java] Judgment of identity and equivalence