TreeSet是唯一有序的,如果是基本数据类型,它会按着自然顺序由小到大输出,但是涉及到自定义类型,就会涉及到各个属性比如我们自定义一个类Student,需要实现Comparable接口,实现自定义类型的排序

class Student implements Comparable<Student> {
String name;
int sid;
double score;

public Student(String name, int sid, double score) {
super();
this.name = name;
this.sid = sid;
this.score = score;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(score);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + sid;
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(score) != Double
.doubleToLongBits(other.score))
return false;
if (sid != other.sid)
return false;
return true;
}

@Override
public String toString() {
return "Student [name=" + name + ", sid=" + sid + ", score=" + score
+ "]";
}

public int compareTo(Student o) {
// 按照Student类的id输出
return this.sid-o.sid;
}

}

测试程序结果是否符合要求:


public class SetTest {

public static void main(String[] args) {
Set<Student> set = new TreeSet<Student>();
set.add(new Student("宝玉", 1, 89));
set.add(new Student("黛玉", 2, 87));
set.add(new Student("袭人", 5, 87));
set.add(new Student("宝钗", 4, 87));
set.add(new Student("花花", 3, 89.9));
for (Student student : set) {
System.out.println(student);

}
}

}


输出结果


Student [name=宝玉, sid=1, score=89.0]
Student [name=黛玉, sid=2, score=87.0]
Student [name=花花, sid=3, score=89.9]
Student [name=宝钗, sid=4, score=87.0]
Student [name=袭人, sid=5, score=87.0]