//没有重构equals方法。
//Cat.java
public class Cat{}
//Program.java
public class Program{
public static void main(String[] args){
Cat cat1 = new Cat();
Cat cat2 = new Cat();
System.out.println(cat1.equals(cat2)); //false
String s1 = new String();
String s2 = new String();
System.out.println(s1.equals(s2)); // 同样是对象,此处为何是true ?
}
}
3 回答
yanrun
TA贡献317条经验 获得超240个赞
看一下String的源码 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; }
就是把两个String转换成字符串数组然后遍历比较
添加回答
举报
0/150
提交
取消