问题
In java the "==" operator compares values for primitive types and compares the reference to the objects location in memory for reference types.
For example:
Primitive Types
int x = 5;
int y = 5;
System.out.println(x == y); //true
Reference Types
String stringOne = new String("Hello");
String stringTwo = new String("Hello");
System.out.println(stringOne == stringTwo); //false
So I guess my question really is, is this distinction true? Because most documents online on this operator do not specify between primitive types and reference types. At most the say that this an equality operator and that for reference types that it cannot be used and we need to use .equals()
if we want to compare values.
So does the "==" operator compare values for primitive types and compare references for reference types?
回答1:
When using the == operator for reference types, what is being evaluated is whether or not the two references point to the same object in memory. This can be misleading (specifically when dealing with Strings) due to the String pool. Each String literal you write is initialized as a String in the pool at runtime, but the same literal will not be initialized twice, they will both point to the same object. Because of this, you will find that
"hello" == "hello"
will equate to true, but
new String("hello") == new String("hello")
equates to false. This happens because in the second case, you created two new objects, whereas in the first case, the two String literals both point to the same object in the String pool.
The .equals() method is usually overridden to determine if two Objects can be treated as "equal" in terms of the values they hold. Using stringOne and stringTwo from your example above, the following expression equates to true:
stringOne.equals(stringTwo)
来源:https://stackoverflow.com/questions/60796257/how-is-the-equality-operator-used-between-primitive-types-and-reference-typ