java中String类eqauls()和==的区别

  在java中“==”和equals()方法的作用都是对地址的比较。equals()是在Object这个超类中定义的。

public boolean equals(Object obj) {
    return (this == obj);
    }
但是由于String、Math等封装类都对equals()方法进行了重写,有些情况下两者的功能是不相同的。下面是String的equals()方法:
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = offset;
        int j = anotherString.offset;
        while (n-- != 0) {
            if (v1[i++] != v2[j++])
            return false;
        }
        return true;
        }
    }
    return false;
    }

可以看出来,String类的equals()方法比较的是两个对象的值而不是地址。

示例1:

String a=new String("hello");
String b=new String("hello");
if(a==b)
System.out.print("true");
else System.out.print(false);

由于a和b的地址值不一样,所以输出结果是false。

String a=new String("hello");
String b=new String("hello");
System.out.print(a.equals(b));
由于比较的是内容,所以这次输出结果是true。

示例二:

String a="hello";
String b="hello";
if(a==b)
System.out.print("true");
else System.out.print(false);

输出结果为true。

分析:这种创建字符串方法是存放在String pool里的,系统为了节省开销pool里只创建了一个“hello”(或者说将两个“hello“合并),a空间和b空间都存放的是这同一个“hello”的地址,因此a==b为返回true。


总结:

基本数据类型也是一样,值都存放在常量池,具有相同值的变量空间里存放的是同一个地址(常量池里不会有两个值相同的数据)。因此对于基本数据类型可以用“==”比较他们值是否相等。对于引用变量却不能用,因为对于两个内容相同的引用变量,系统并不会将他们的内容合并为一处。这是由他们的存储方式决定的。

猜你喜欢

转载自blog.csdn.net/xlantian/article/details/79547064