【问题标题】:Equality operator bevaiour for dynamically passed string values in java [duplicate]在java中动态传递字符串值的相等运算符bevaiour [重复]
【发布时间】:2016-04-11 13:32:20
【问题描述】:
public class EqualsCheck {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        Scanner sc1= new Scanner(System.in);
        String s1 = sc.next();
        String s2 = sc1.next();
        equalCheck(s1,s2);
    }

    private static void equalCheck(String s1, String s2) {
        //Using Assignment
        System.out.println(s1 == s2);

        //Using equals

        System.out.println(s1.equals(s2));

        //Printing HashCode

        System.out.println("s1 :"+s1.hashCode()+" s2: "+s2.hashCode());
    }
}

传递的字符串是:

 s1 = "abc";
 s2 = "abc";

如果我执行s1==s2,它会返回false。为什么字符串池在这里不起作用。

【问题讨论】:

  • s1.equals(s2) 按预期返回 true。
  • 我投票结束这个问题作为离题,因为这个问题之前已经回答过一百万次了
  • “使用赋值”这里没有赋值。这是使用 identity.
  • 不涉及任何字符串池。您正在从 sc 读取两个新字符串。

标签: java string string-pool equality-operator


【解决方案1】:

字符串池在这里不起作用,因为您没有将字符串放入字符串池中。

对于在运行时构造的字符串,这不会自动发生。您需要致电 String.intern() 这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 2019-08-29
    • 1970-01-01
    相关资源
    最近更新 更多