Java中String类的equals方法理解

1、Object中equals方法java

       咱们知道,在Java中,Object类是全部其余类的父类,java中只是单继承的,Object类中有不少方法,常见的好比有toString()、hashcode()、equals()、wait()、notify()等等。其中equals方法至关于"==",比较的是内存地址。ui

2、String重写equals方法this

       简而言之,String类默认继承Object类,固然也继承了Object类中的equals()方法,String重写了equals()方法,比较的是字符串的值。例子以下spa

package thinkinjava;


public class StringTest {


private String name;


public StringTest() {
super();
}


public StringTest(String name) {
super();
this.name = name;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public static void main(String[] args) {
String xx = new String("xxx");
String xx1 = new String("xxx");


System.out.println(xx.equals(xx1)); // true说明string重写了Object类中equals方法,比较的字符串的值


StringTest xx2 = new StringTest("xxx");
StringTest xx3 = new StringTest("xxx");


System.out.println(xx2.equals(xx3));


StringBuilder xx4 = new StringBuilder("xxx");
StringBuilder xx5 = new StringBuilder("xxx");


System.out.println(xx4.equals(xx5));


StringBuffer sb = new StringBuffer("xxx");
StringBuffer sb1 = new StringBuffer("xxx");


System.out.println(sb.equals(sb1));
}
}
code


结果分别是:true
false
false
false对象

结果分析:咱们从第一个true发现,两个不一样的对象由于字符串的值相等,证明了String重写了Object类中的方法,比较的是字符串的值。继承