*关于==Object==类
== 与 equals的差别:
==比较的是地址,后者比的是内容
String方法中的equals是比较内容,Object中的equals方法和 = =一样,也是判断地址的。
为了增加equals的实用性,要将Object中的方法改为比较内容,就要重写equals方法:
package java1108;
class Demo11{
int age;
String name;
Demo11(int age,String name){
this.age = age;
this.name = name;
}
public boolean equals(Object anObject) {
if(this == anObject) {
return true;
}
if(anObject instanceof Demo11) {
Demo11 anotherdemo = (Demo11)anObject;
if(this.name.equals(anotherdemo.name) && this.age ==anotherdemo.age) {
return true;
}
return false;
}
return false;
}//重写equals方法
}
public class Test11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo11 d1 = new Demo11(18,"wanting");
Demo11 d2 = new Demo11(18,"wanting");
System.out.println(d1 == d2);
System.out.println(d1.equals(d2));//Object类中的equals方法也是比较的地址
}
}
运行结果:
*关于==字符串创建过程==的详解: