Java中一个奇怪的字符串赋值现象

发布于 2024-12-25 03:47:23 字数 856 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

这样的小城市 2025-01-01 03:47:23

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.

像极了他 2025-01-01 03:47:23

因为 == 比较引用,并且 abcbcd 都指向两个相同的内存位置。 @jan Zyka 建议的 equals() 函数是比较两个不同字符串的正确选项。

但是,如果您有意希望abcbcd都指向相同的内存位置,您可以使用String类的intern()方法。 .. 请此处阅读文档。

Because the == compares the references and both abc and bcd 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 and bcd should point the same memory location, You can use intern() method of String class... read documentation here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文