==和.equals()的区别

来源:互联网 发布:什么软件可以看美剧 编辑:程序博客网 时间:2024/04/30 06:15

原文链接 How do I compare strings in Java?

  • == 执行的是 引用相等性的比较
  • .equals() 执行的是 值相等性的比较

Objects.equals() 相比于 .equals()可能是更好的选择,该方法会在比较前检查对象是否为null。

// These two have the same valuenew String("test").equals("test") // --> true // ... but they are not the same objectnew String("test") == "test" // --> false // ... neither are thesenew String("test") == new String("test") // --> false // ... but these are because literals are interned by // the compiler and thus refer to the same object"test" == "test" // --> true // ... but you should really just call Objects.equals()Objects.equals("test", new String("test")) // --> trueObjects.equals(null, "test") // --> false

附上String::equals()源码:

public boolean equals(Object anObject) {        if (this == anObject) {            return true;        }        if (anObject instanceof String) {            String anotherString = (String)anObject;            int n = value.length;            if (n == anotherString.value.length) {                char v1[] = value;                char v2[] = anotherString.value;                int i = 0;                while (n-- != 0) {                    if (v1[i] != v2[i])                        return false;                    i++;                }                return true;            }        }        return false;    }
0 0