k*******t 发帖数: 202 | 1 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Foo {
String name;
int number;
List friends;
public boolean equals(Object obj)
{
System.out.println(friends);
System.out.println(test.friends);
System.out.println(test.name);
System.out.println(this.name);
return number == test.number
&& (name == test.name
|| (name != null && name.equals(test.name)))
&& ((friends !=null) && friends.equals(test.friends));
}
}
public static void main(String args[])
{
Foo a = new Foo();
Foo b = new Foo();
a.number =10;
b.number = 10;
a.name = "test";
b.name = "testme";
boolean test = a.equals(b);
a.friends =new ArrayList();
b.friends =new ArrayList();
a.friends.add("Jack");
a.friends.add("Paul");
b.friends.add("Jack");
b.friends.add("Paul");
System.out.println(a.friends.equals(b.friends));
System.out.println(test);
}
想override Objects的equals 函数,但是跑了一下程序,发现调用a.equals(b)的时候
, a.friends 和b.friends的值都没有传进去。高手请指点,多谢了! |
d**e 发帖数: 6098 | 2 大致上,如果要override Object.equals函数,可以是
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(!(obj instanceof Foo)) {
return false;
}
Foo other = (Foo) obj;
boolean result = this.number == other.number;
if(!result) {
return false;
} else {
if(this.name != null) {
result = this.name.equals(other.name);
} else {
result = (other.name == null);
}
if(!result) {
return false;
} else {
// other object members..
....
}
}
// 如果可以调用其它library的话就简单很多
// 我比较喜欢用apache commns的EuqalsBuilder
// http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/builder/EqualsBuilder.html
}
下面code里还有些回复。
test是什么?
对String name,== 是identity equal,我觉得这里用不好。
但equals没有重新call,所以这个是friends.add之前的值。
【在 k*******t 的大作中提到】 : import java.util.ArrayList; : import java.util.HashMap; : import java.util.List; : public class Foo { : String name; : int number; : : List friends; : public boolean equals(Object obj) : {
|
k*******t 发帖数: 202 | 3 谢谢楼上的答复。
请问下,用instanceof有什么弊端吗? |
w**z 发帖数: 8232 | 4 No static checking, compiler and tools cannot help you, and it's slow.
【在 k*******t 的大作中提到】 : 谢谢楼上的答复。 : 请问下,用instanceof有什么弊端吗?
|
k*******t 发帖数: 202 | 5
相比之下,用if(this == null || this.getClass()!= obj.getClass()) 会安全一些
吗?
【在 w**z 的大作中提到】 : No static checking, compiler and tools cannot help you, and it's slow.
|
w**z 发帖数: 8232 | 6 I meant in general, you should avoid using instanceof, try to use override
method. But implementing equals is the exception. Sorry about the confusion.
【在 k*******t 的大作中提到】 : : 相比之下,用if(this == null || this.getClass()!= obj.getClass()) 会安全一些 : 吗?
|