Comparator和Comparable接口
内部比较器 : implements Comparable(java.lang.Comparable) 接口)
外部比较器:implements Comparator(java.util.Comparator)接口(内部类也是用这个)
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
/**
* 功能:存储并输出学生的信息
* 1。内部比较器 : implements Comparable(java.lang.Comparable 接口)
* 2.外部比较器
* @author ACCI
*
*/
public class TestTreeSet3 {
public static void main(String[] args) {
//内部比较器
Set<StudentTreeSet> stu = new TreeSet<StudentTreeSet>();
stu.add(new StudentTreeSet(1, "aaa", 20, 60));
stu.add(new StudentTreeSet(5, "bbb", 17, 80));
stu.add(new StudentTreeSet(2, "ccc", 18, 70));
stu.add(new StudentTreeSet(3, "ddd", 19, 80));
stu.add(new StudentTreeSet(4, "eee", 21, 90));
stu.add(new StudentTreeSet(1, "aaa", 20, 60));//重复
stu.add(new StudentTreeSet(2, "bbb", 18, 70));
System.out.println(stu.size());
System.out.println(stu);
System.out.println("--------------");
//内部类 比较
Set<StudentTreeSet> stu1 = new TreeSet<StudentTreeSet>(new Comparator<StudentTreeSet>(){
@Override
public int compare(StudentTreeSet stu1, StudentTreeSet stu2) {
if (stu1.getNo()-stu2.getNo()>0) {
return 1;
}else if (stu1.getNo()-stu2.getNo()<0) {
return -1;
}else {
//主要的比较完之后比较次要的
if (stu1.getName().compareTo(stu2.getName())>0) {
return 1;
}else if (stu1.getName().compareTo(stu2.getName())<0) {
return -1;
}else {
return 0;
}
}
}
});
stu1.add(new StudentTreeSet(1, "aaa", 20, 60));
stu1.add(new StudentTreeSet(5, "bbb", 17, 80));
stu1.add(new StudentTreeSet(2, "ccc", 18, 70));
stu1.add(new StudentTreeSet(3, "ddd", 19, 80));
stu1.add(new StudentTreeSet(4, "eee", 21, 90));
stu1.add(new StudentTreeSet(1, "aaa", 20, 60));//重复元素
stu1.add(new StudentTreeSet(2, "bbb", 18, 70));
System.out.println(stu1.size());
System.out.println(stu1);
}
}
public class StudentTreeSet implements Comparable<StudentTreeSet>{
private int no;
private String name;
private int age;
private int score;
public StudentTreeSet() {
super();
// TODO Auto-generated constructor stub
}
public StudentTreeSet(int no, String name, int age, int score) {
super();
this.no = no;
this.name = name;
this.age = age;
this.score = score;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(StudentTreeSet otherStudent) {
if (this.getNo()-otherStudent.getNo()>0) {
return 1;
}else if (this.getNo()-otherStudent.getNo()<0) {
return -1;
}else {
//主要的比较完之后比较次要的
if (this.getName().compareTo(otherStudent.getName())>0) {
return 1;
}else if (this.getName().compareTo(otherStudent.getName())<0) {
return -1;
}else {
return 0;
}
}
}
@Override
public String toString() {
return "StudentTreeSet [no=" + no + ", name=" + name + ", age=" + age + ", score=" + score + "]\n";
}
}