String中"=="和equal()的区别

来源:互联网 发布:可以拍电影的软件 编辑:程序博客网 时间:2024/05/18 01:53

转载:http://blog.csdn.net/l975764577/article/details/20856833


==是判断两个字符窜引用是否相等。

.equal()判断的是两个字符串字面值是否相等

下面是JDK源码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;
    }

我们可以看到,equals()方法首先通过this指针来判断两个对象是否相等,如果相等返回true,不相等的话则检查传入的参数是否是一个String实例,如果是的话得到参数的长度并且与要比较的String对象长度做比较如果不相等则返回字符串不相等,如果相等则分别得到两个字符串内的字符组,循环对两个字符串组一一进行比较,如果全相等的话则返回两个字符串相等,否则返回两个字符串不相等。

不同对象总是产生不同的散列值,即便是他们是相等的值也可以。


因此,如果你想要判断两个字符串是否相等你最好使用.equal()方法,除非在一些特殊情况下你能保证当前两个string的值代表的是同一个对象。
下面是一些测试==方法的类别:
/ These two have the same value
new String("test").equals("test") // --> true 


// ... but they are not the same object
new String("test") == "test" // --> false 


// ... neither are these
new 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 


// concatenation of string literals happens at compile time,
// also resulting in the same object
"test" == "te" + "st" // --> true


// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) // --> false


// interned strings can also be recalled by calling .intern()
"test" == "!test".substring(1).intern() // --> true
我们都应该知道==相对于equal方法来说更轻量级,在你能保证两个string值指向同一个对象时你就可以使用==方法并且它能带给你性能上的提升。当然,这种提升也是很少的。
equal()方法的使用
某些情况下我们要覆写equal()的方法,我们也一定要覆写.tohashcode()方法,不然可能带来意想不到的的结果
0 0
原创粉丝点击