可能的重复: Java 中
Equals 和 ==
字符串比较和字符串实习之间的区别
这次很不言自明的问题。
编辑:我理解 == 不等于。我不明白为什么 "a" == "a" 中的 a 都被分配或视为相同的对象实例(它们是)。
编辑有人读过这个问题还是只是喜欢按下关闭按钮?它与上述任何一个都没有关系。告诉我我在哪里提到 Equals 方法......
可能的重复: Java 中
Equals 和 ==
字符串比较和字符串实习之间的区别
这次很不言自明的问题。
编辑:我理解 == 不等于。我不明白为什么 "a" == "a" 中的 a 都被分配或视为相同的对象实例(它们是)。
编辑有人读过这个问题还是只是喜欢按下关闭按钮?它与上述任何一个都没有关系。告诉我我在哪里提到 Equals 方法......
"a" == "a"
给出 true ,因为 "a" 将被视为字符串文字并被池化。因此,两个“a”都指向同一个实例,因为两个引用都指向同一个对象,== 返回 true。
当你说new String("a")
。全新的对象会在 Heap 和不同的引用上创建,所以 == 返回 false,你需要使用.equals()
.
==
checks for equality in references (pointers of memory)"a"
is a string literal and it's stored in constant data table (so that every use of it will point to the same literal)new String("a")
allocates a string object with the content of "a" but it is a stand alone object with is own memory space.new
always allocates a different obect, so two allocated object can't have same reference你必须使用 "a".equals("a");
When you use new String("a")
it creates a new memory location. When you're comparing objects (String is an Object) with == it compares the memory locations and thus you get false. The new
forced it to create 2 different memory locations. The "a" == "a" compares the memory locations for each and since they are string literal's they have same memory reference. The proper way to compare string is to use the .equals()
method from the String class.
"a" == "a"
- Here process keept this string in a text segment, which is read only data. And you are just comparing the address of the text segment where this string is present. Which will give you true.
But new String("a")
will allocate memory dynamically in heap and it will copy the string "a"
to that dynamically allocated place. So new String("a") = new String("a")
will allocate memory two times in heap. And you are comparing those two address its absolutely different. Because it has allocated memory in heap two times.
Java creates a string-pool for strings that are know in design time. If you write something like
string a = "a"; string b = "b"; a == b will return true because java creates only one object with the same address.
If you write something like
new String("a") == new String("b")
this will return false because two objects are created during runtime with different addresses.
The == operator compares the addresses of the objects, not the values.