public class TestEquals {
String name;
TestEquals(String name) {
this.name = name;
}
public static void main(String[] args) {
String s1 =new String("hello");
String s2 =new String("hello");
String s3 ="hello";
String s4 ="hello";
System.out.println(s1.equals(s2));
//String 类重写了equals方法;所以返回 true;
System.out.println(s3.equals(s4));
System.out.println(s3==s4);
//不是对象类型,所以位于方法区,方法区只能存在一个"hello";所以二者指向的是统一对象;
//所以地址也一样;
TestEquals t1 =new TestEquals("he");
TestEquals t2 =new TestEquals("he");
System.out.println(t1.equals(t2));
//首先返回的是false;
//重写了equals 方法后,返回true;
}
public boolean equals(Object obj) {
if(this==null) {
return false;
}
if(this.getClass()!=obj.getClass()) {
return false;
}else {
TestEquals t = (TestEquals)obj;
if(this.name!=t.name) {
return false;
}
}
return true;
}
}
String name;
TestEquals(String name) {
this.name = name;
}
public static void main(String[] args) {
String s1 =new String("hello");
String s2 =new String("hello");
String s3 ="hello";
String s4 ="hello";
System.out.println(s1.equals(s2));
//String 类重写了equals方法;所以返回 true;
System.out.println(s3.equals(s4));
System.out.println(s3==s4);
//不是对象类型,所以位于方法区,方法区只能存在一个"hello";所以二者指向的是统一对象;
//所以地址也一样;
TestEquals t1 =new TestEquals("he");
TestEquals t2 =new TestEquals("he");
System.out.println(t1.equals(t2));
//首先返回的是false;
//重写了equals 方法后,返回true;
}
public boolean equals(Object obj) {
if(this==null) {
return false;
}
if(this.getClass()!=obj.getClass()) {
return false;
}else {
TestEquals t = (TestEquals)obj;
if(this.name!=t.name) {
return false;
}
}
return true;
}
}