public class TreeSetTest {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new StudentComparator());
ts = getStudent();
Iterator it = ts.iterator();
while(it.hasNext()){
Student s = it.next();
System.out.println(s);
}
}
//定义一个方法从键盘获取字符串,转换成为Student对象
public static TreeSet getStudent(){
TreeSet ts = new TreeSet(new StudentComparator());
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名,分数:");
while(true){
String s = sc.nextLine();
//首先判断条件被我写成 s.trim()=="";讽刺啊,==判断的是两个的地址值。。。,至少也应该写成s.equals("");
if(s.isEmpty())
break;
String[] st = s.trim().split(" +");
Student student = new Student();
student.setName(st[0]);
student.setScore(Integer.parseInt(st[1]));
ts.add(student);
// System.out.println("请输入姓名,分数:");
}
System.out.println("结束输入!");
return ts;
}
}
另外:比较器的代码如下:
public class StudentComparator implements Comparator{
public int compare(Student s1,Student s2){
// int num = s1.getName().compareTo(s2.getName());
// return 0==num?s1.getScore()-s2.getScore():num;
int num = s1.getScore()-s2.getScore();
return 0==num?s1.getName().compareTo(s2.getName()):num;
}
}