写成这样,就行了。 class Value { Value(int i) { this.i=i; } boolean equals(int j) { if (i==j) return true;
return false; } private int i; }class EqualsMethod2 { public static void main(String[] args) { Value v1=new Value(100); Value v2=new Value(100); System.out.println(v1.equals(v2)); } }
我错了。你程序中的v1.equals(v2),比较的是两个对像变量,而不是i的值。 两个对像变量当然不同啦。 如果是这样: Value v1 = new value(100); Value v2 = v1; 那么结果就对了。如果你要比较其中的i值的话,程序应该这样写的。 class Value { Value(int i) { this.i=i; } int geti() { return i; } boolean equals(Value j) { if (i==j.geti()) return true;
return false; } private int i; }class EqualsMethod2 { public static void main(String[] args) { Value v1=new Value(100); Value v2=new Value(100); System.out.println(v1); System.out.println(v2); System.out.println(v1.equals(v2)); } }
v1和v2是不同的handle. v1.i = v2.i;
v1和v2是两个引用。代表不同的对象。 equals()继承的是Object的equals(),for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true). 所以不会相等。但是: String s1=new String("100"); String s2=new String("100"); s1.equals(s2);返回 true. 因为String 重新定义了equals().
上面的那位兄台 有一个问题” class Value { Value(int i) { this.i=i; } boolean equals(int j) { if (i==j) return true;
return false; } int get_i(){ return i;} private int i; }class EqualsMethod2 { public static void main(String[] args) { Value v1=new Value(100); Value v2=new Value(100); System.out.println(v1.equals(v2.get_i())); } }
class Value
{
Value(int i)
{
this.i=i;
}
boolean equals(int j)
{
if (i==j) return true;
return false;
} private int i;
}class EqualsMethod2
{
public static void main(String[] args)
{
Value v1=new Value(100);
Value v2=new Value(100);
System.out.println(v1.equals(v2));
}
}
两个对像变量当然不同啦。
如果是这样:
Value v1 = new value(100);
Value v2 = v1;
那么结果就对了。如果你要比较其中的i值的话,程序应该这样写的。
class Value
{
Value(int i)
{
this.i=i;
} int geti()
{
return i;
} boolean equals(Value j)
{
if (i==j.geti()) return true;
return false;
} private int i;
}class EqualsMethod2
{
public static void main(String[] args)
{
Value v1=new Value(100);
Value v2=new Value(100);
System.out.println(v1);
System.out.println(v2);
System.out.println(v1.equals(v2));
}
}
v1.i = v2.i;
equals()继承的是Object的equals(),for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).
所以不会相等。但是:
String s1=new String("100");
String s2=new String("100");
s1.equals(s2);返回 true.
因为String 重新定义了equals().
有一个问题”
class Value
{
Value(int i)
{
this.i=i;
}
boolean equals(int j)
{
if (i==j) return true;
return false;
} int get_i(){
return i;}
private int i;
}class EqualsMethod2
{
public static void main(String[] args)
{
Value v1=new Value(100);
Value v2=new Value(100);
System.out.println(v1.equals(v2.get_i()));
}
}
v1和v2它们不是同一个对象,当然不能得到true了。但如果是两个string那
情况就不一样了。