【问题标题】:Why string.equals not working in my case? [closed]为什么 string.equals 在我的情况下不起作用? [关闭]
【发布时间】:2020-03-11 10:12:42
【问题描述】:

下面有一个例子:

public static void main(String[] args) {
        String a = "abc@gmail.com";
        System.out.println(a.hashCode());
        System.out.println(String.format("%x%n", a.hashCode()));
        String text1 = String.format("%x%n", a.hashCode());
        String text2 = "9f4e93d3";
        if (text1.equals(text2)) {
            System.out.println("equals");
        } else {
            System.out.println("not equals");
        }
    }

我的结果:

-1622240301
9f4e93d3

not equals

我不知道为什么我的代码不输出“等于”。谁能帮我解释一下?
谢谢你。

【问题讨论】:

  • 两个字符串不相等。其中一个在末尾有一个换行符,因为您将 %n 放在格式字符串中。
  • @khelwood 啊,我的错。非常感谢。

标签: java core


【解决方案1】:

如果将 .trim() 用于“text1.trim()”,则可以达到“等于”。像这个。 text1 的值在 9f4e93d3 之后还有更多字符。

text1 是 9f4e93d3\r\n

text2 只是 9f4e93d3

如果您在调试模式下运行此应用,您可以轻松查看。

    public static void main(String[] args) {
        String a = "abc@gmail.com";
//        System.out.println(a.hashCode());
//        System.out.println(String.format("%x%n", a.hashCode()));
        String text1 = String.format("%x%n", a.hashCode()); 
        String text2 = "9f4e93d3";
        System.out.println(text1+"-"+text2);
        if (text1.trim().equals(text2)) {
            System.out.println("equals");
        } else {
            System.out.println("not equals");
        }
    }

输出:

9f4e93d3
-9f4e93d3
equals

【讨论】:

  • 9f4e93d3 与 -9f4e93d3 是如何相等的?
  • @LajosArpad System.out.println(text1+"-"+text2);text1\n 结尾
  • 如果你把断点放在 main 之后的第一行。运行调试模式后,您可以继续在 Eclipse 上跳过“f6”,并且可以查看任何变量的值。实际上我看到 text1 is '9f4e93d3\r\n' 通过使用调试模式
  • 我明白了。谢谢弗里吉
【解决方案2】:

text1.length()=9 (text1 = 9f4e93d3\n)

text2.length()=8 (text2 = 9f4e93d3),

由于没有相同的 text1.equals(text2) 计算结果为 false。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2018-07-15
    • 2021-09-29
    • 2017-02-22
    • 1970-01-01
    • 2016-08-27
    相关资源
    最近更新 更多