String与Object的equals的对比学习
1.比较不同形式的String对象equals
在进入研究之前,先上一段代码:
String s=new String("abc");
String s1="abc";
Object s2="abc";
String s3="a"+"b"+"c";
System.out.println(s);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s.equals(s1));
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s2.equals(s3));
结果:
abc
abc
abc
abc
true
true
true
true
很显然,无论是怎样的String进行equals对比相同字符串都会返回true,这是小明同学就说啦:“连个一样的字符串比较结果一定是true啦,这傻子都知道”
好的,接下来我们进行进一步学习。
2.Object的equals的研究
首先,我们先定义一个测试类,定义一个属性name,写构造方法
import java.util.Objects;
public class test01 {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public test01(String name) {
this.name = name;
}
public test01() {
}
}
然后在mian中测试
test01 t1=new test01("Jim");
test01 t2=new test01("Jim");
test01 t3=t1;
System.out.println(t3.equals(t1));
System.out.println(t1.equals(t2));
结果:
true
false
到这里,估计好多人都会有疑惑了,"相同"的对象,为什么会出现这种情况呢,我们来看Object的equals方法:
public boolean equals(Object obj) {
return (this == obj);
}
可以很明显的看到返回值是判断两个Object对象的地址,在我们的测试代码中,t1与t3是有相同的地址的,然而t2却是先创建出的一个对象,它拥有不同的地址,所以在equals时返回值为false。
那么这时候我们再看String的equals方法:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (!COMPACT_STRINGS || this.coder == aString.coder) {
return StringLatin1.equals(value, aString.value);
}
}
return false;
}
我们可以在源码中看出,其不仅比较了两者地址是否相同,如果不相同,在二者coder(我在这里理解是编码)相同的时候,运用StringLatin1.equals判断自身的value与目标字符串value是否相同,其中StringLatin1.equals的方法主体如下:
@HotSpotIntrinsicCandidate
public static boolean equals(byte[] value, byte[] other) {
if (value.length == other.length) {
for (int i = 0; i < value.length; i++) {
if (value[i] != other[i]) {
return false;
}
}
return true;
}
return false;
}
我们可以明显看到此方法是先判断二者的长度,在进行迭代逐一比对每一个索引值位置的字符。
到此我们就可以理解为什么不同方式创建的相同字符串equals时为什么结果为true。
接下来对我们的测试类重写equals方法使得我们创建的”相同“的对象在equal时返回值为false,在test01中我们添加两个重写函数
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
test01 test01 = (test01) o;
return name.equals(test01.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
此时再运行测试代码即可得到true。
初次写下博客,如有错误希望得到指点改正。