怎么样让TreeSet判断两元素是否相同?
代码如下:
---------------------------------------------------------------------------------------------------------------------
import java.io.*;
import java.util.*;
class Per implements Comparable<Per> {
public String name;
public String StudentNumber;
public int score;
public Per(String name, String StudentNumber, int score) {
this.name=name;
this.StudentNumber=StudentNumber;
this.score=score;
}
public String toString() {
return this.name+" "+this.StudentNumber+" "+this.score;
}
public boolean equals(Object obj) {
if (this==obj)
return true;
if (!(obj instanceof Per))
return false;
Per per=(Per)obj;
if (this.StudentNumber.equals(per.StudentNumber))
return true;
else
return false;
}
public int hashCode() {
return this.StudentNumber.hashCode();
}
public int compareTo(Per per) {
if (this.StudentNumber.equals(per.StudentNumber))
return 0;
else if (this.score > per.score)
return -1;
else
return 1;
}
}
public class Test14 {
public static void main(String[] args) {
Set<Per> set=new TreeSet<Per>();
set.add(new Per("sl", "9007", 100));
set.add(new Per("li", "9005", 2));
set.add(new Per("ly", "9006", 2));
set.add(new Per("ly", "9006", 64));
System.out.println(set);
}
}
这段代码输出结果为:[sl 9007 100, ly 9006 64, li 9005 2, ly 9006 2],并没有把学号同为9006的看成重复元素
所以怎么样让TreeSet判断两元素是否相同?