您好我正在尝试覆盖我的自定义类的等号和哈希码方法。
这是我的自定义类
public class property
{
public String type = null;
public int value;
public int id;
public String name = null;
public String course = null;
public property(String type, String course, int value, int id)
{
this.value = value;
this.type = type;
this.course = course;
this.id = id;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
property sig = (property) obj;
if(sig != null) {
if(sig.type.equals("EST1")) {
if (sig.name != null && sig.type != null && sig.course != null) {
Log.d("property", "Other " + sig.course + "AHHAHAHA " + course + "shahahaaha " + sig.id + "babababaab " + id);
if (sig.course.equals(this.course) && sig.value == this.value && sig.type.equals(this.type) && sig.id == (this.id)) {
Log.d("property", "EST1");
return true;
}
}
}
return false;
}
问题是“this.id,this.type”总是为null或0我不明白为什么...而sig.id,sig.type有值。只是为了让你知道它只是代码片段,而不是完整的代码所以它可能有拼写错误而且在逻辑上不正确..
答案 0 :(得分:1)
你的代码在我身边运作良好,所以我猜你的测试程序与我的有些不同(或复杂?)。
我试过以下进行测试,
property p = new property("a","b", 100, 200);
System.out.println("id:"+p.id);
System.out.println("type:"+p.type);
System.out.println(p.equals(p) +" should be true..");
我得到了,
id:200
type:a
true should be true..