How is the “==” Equality Operator Used Between Primitive Types and Reference Types? [duplicate]

流过昼夜 提交于 2020-08-10 19:27:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!