Java中一个奇怪的字符串赋值现象
public static void main(String[] args){
/* lots of codes */
if(profile.addFriend(buffernametwo)){
boolean a = profile.addFriend(buffernametwo);
System.out.println(a);
//prints false; however if I directly put profile.addFriend(buffernametwo)
//and follow the debugger, it will appear true
/* lots of codes */
}
/* lots of codes */
//the following method is in a different class
public boolean addFriend(String friend) {
for(int i = 0;i < profile_friend.size();i++){
//Here is the point
if(friend == profile_friend.get(i)){
return false;
}
}
profile_friend.add(friend);
return true;
/* lots of codes */
private ArrayList<String> profile_friend = new ArrayList<String>();
}
问题在代码注释中
public static void main(String[] args){
/* lots of codes */
if(profile.addFriend(buffernametwo)){
boolean a = profile.addFriend(buffernametwo);
System.out.println(a);
//prints false; however if I directly put profile.addFriend(buffernametwo)
//and follow the debugger, it will appear true
/* lots of codes */
}
/* lots of codes */
//the following method is in a different class
public boolean addFriend(String friend) {
for(int i = 0;i < profile_friend.size();i++){
//Here is the point
if(friend == profile_friend.get(i)){
return false;
}
}
profile_friend.add(friend);
return true;
/* lots of codes */
private ArrayList<String> profile_friend = new ArrayList<String>();
}
The question is in the comment of the code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java中有一个字符串池,因此它们恰好具有相同的引用。但您不应该依赖于此,并且在比较字符串时始终使用
equals()
。There is a String pool in Java so here they coincidentaly have the same reference. But you shouldn't rely on this and always use
equals()
when comparing Strings.因为 == 比较引用,并且
abc
和bcd
都指向两个相同的内存位置。 @jan Zyka 建议的 equals() 函数是比较两个不同字符串的正确选项。但是,如果您有意希望
abc
和bcd
都指向相同的内存位置,您可以使用String类的intern()
方法。 .. 请此处阅读文档。Because the == compares the references and both
abc
andbcd
are pointing to two same memory location.equals()
function suggested by @jan Zyka is the correct option to compare two different strings.However if you intentionally want that both the
abc
andbcd
should point the same memory location, You can useintern()
method of String class... read documentation here.