1. 程式人生 > >Java-Set集合(2)

Java-Set集合(2)

比較器排序

  • 比較器排序:
    採用有參構造,構造的引數就要一個比較器
 TreeSet(Comparator<? super E> comparator)
  • 在建立TreeSet 物件的時候,傳進來一個比較器的子類物件
    根據子類物件重寫比較器中compare 方法,根據此方法的返回值的正負和0,來排序元素,返回0就不往裡面存
    a.構造一個新的空 TreeSet,它根據指定比較器進行排序。
    b.介面 Comparator 比較器
    c.int compare(T o1, T o2) 比較方法
    d.比較用來排序的兩個引數。
public
class MyTest3 { public static void main(String[] args) { TreeSet t = new TreeSet<>(new Comparator<Integer>() { @Override public int compare(Integer s1, Integer s2) { return s1 - s2; } }); t.add(6); t.add(6
); t.add(3); t.add(2); t.add(1); t.add(4); t.add(5); t.add(4); t.add(3); System.out.println(t); //[1, 2, 3, 4, 5, 6] } }
  • 舉例:鍵盤錄入3個學生資訊(姓名,語文成績,數學成績,英語成績),按照總分從高到低輸出到控制檯。
//Student類
public class Student {
    private String name;
    private
double mathScore; private double englishScore; private double totalScote; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getMathScore() { return mathScore; } public void setMathScore(double mathScore) { this.mathScore = mathScore; } public double getEnglishScore() { return englishScore; } public void setEnglishScore(double englishScore) { this.englishScore = englishScore; } public double getTotalScote() { return this.englishScore+this.mathScore; } } //測試類 public class MyTest2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //比較器排序 TreeSet<Student> treeSet = new TreeSet<Student>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { return (int) (s1.getTotalScote() - s2.getTotalScote()); } }); for (int i = 1; i <= 3; i++) { System.out.println("請輸入學生的姓名"); Student student = new Student(); String name = sc.next(); student.setName(name); System.out.println("請輸入第" + i + "個學生" + name + "的數學成績"); double mathScore = sc.nextDouble(); student.setMathScore(mathScore); System.out.println("請輸入第" + i + "個學生" + name + "的英語成績"); double englishScore = sc.nextDouble(); student.setEnglishScore(englishScore); //把學生物件新增到集合裡面 treeSet.add(student); } System.out.println("姓名" + "\t" + "數學成績" + "\t" + "總分"); for (Student stu : treeSet) { System.out.println(stu.getName() + "\t" + stu.getMathScore() + "\t" + stu.getEnglishScore() + "\t" + stu.getTotalScote()); } } }