public class MyClass{
private String name;
private int num; public MyClass(String string, int i) {
this.name=name;
this.num=num;
}
public static void main(String args[]){
MyClass s1=new MyClass("tom",10);
MyClass s2=new MyClass("tom",10);
String st1=new String("hello!");
String st2=new String("hello!");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println();
System.out.println(st1 == st2);
System.out.println(st1.equals(st2));
}
}
运行结果:
false
falsefalse
true同样是equals
第一个类实例化的两个对象的equals 的值就为flase
第二个的两个对象的equals 的值就为true.求解。。
private String name;
private int num; public MyClass(String string, int i) {
this.name=name;
this.num=num;
}
public static void main(String args[]){
MyClass s1=new MyClass("tom",10);
MyClass s2=new MyClass("tom",10);
String st1=new String("hello!");
String st2=new String("hello!");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println();
System.out.println(st1 == st2);
System.out.println(st1.equals(st2));
}
}
运行结果:
false
falsefalse
true同样是equals
第一个类实例化的两个对象的equals 的值就为flase
第二个的两个对象的equals 的值就为true.求解。。
你的MyClass没有重写equals方法,所以调用的了是Object类的equals方法
Obejct的equals只有同一个对象的时候才会是true;Object o = new Object();o.equals(o)这才能是true;
{
if(o instanceof MyClass)
{
MyClass temp = (MyClass)o;
return (temp.name.equals(this.name) && temp.id==this.id);
}else
{
return false;
}
}
参考:http://topic.csdn.net/u/20110303/10/95e2119a-1124-4b84-a890-928fb997be2f.html
你没有重写所以就会用Object类的equals方法来比较
return (this == obj);
}