我正在尝试运行该程序,但不断收到非法开始表达式的错误,对哈希代码也知之甚少。 如何以正确的方式使用它,这段代码是什么意思?
public class Test1 {
private int num;
private String data;
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null) || (obj.getClass() != this.getClass())
return false;
//objects must be Test at this point
Test test = (Test) obj;
return num == test.num &&
data == test.data || (data != null && data.equals(test.data));
}
public int hashCode() {
int hash = 7;
hash = 31 * hash + num;
hash = 31 * hash + (null == data ? 0 : data.hashCode());
return hash;
}
}
你在equals
方法中的括号对我来说看起来不对......
尝试
if(obj==null || (obj.getClass()!=this.getClass()))
您还需要将强制转换更改为正确的对象类型
Test1 test = (Test1)obj;
我在你的代码中看到了很多语法错误,请尝试在类下面。
public class Test1 {
private int num;
private String data;
public Test1(int num, String data) {
this.num = num;
this.data =data;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
// Objects must be Test at this point.
Test1 test = (Test1) obj;
return num == test.num && data == test.data || (data != null && data.equals(test.data));
}
public int hashCode() {
int hash = 7;
hash = 31 * hash + num;
hash = 31 * hash + (null == data ? 0 : data.hashCode());
return hash;
}
public static void main(String[] args) {
Test1 obj1 = new Test1(1,"one");
Test1 obj2 = new Test1(2,"two");
Test1 obj3 = new Test1(1,"one");
Test1 obj4 = new Test1(2,"two");
System.out.println(obj1.equals(obj2));
System.out.println(obj1.equals(obj3));
System.out.println(obj2.equals(obj3));
System.out.println(obj2.equals(obj4));
}
}