TreeSet 的排序非自然數需要實現Comparator接口

package com;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetDome1 {
 public static void main(String[] args) {
  
  TreeSet<Student> set = new TreeSet<Student>(new MyComparator());

//定義類非自然數進行排序,需要實現Comparator接口裏面的compare方法,new MyComparator(),來標識排序的方法

  Student s1 = new Student(10);
  Student s2 = new Student(20);
  Student s3 = new Student(30);
  Student s4 = new Student(40);
  set.add(s1);
  set.add(s2);
  set.add(s3);
  set.add(s4);
  for(Iterator<Student> iter = set.iterator(); iter.hasNext(); ){
   System.out.println(iter.next().scores);
  }

  System.out.println("minimum value: "+ Collections.min(set,new MyComparator()).scores);//最小值
  System.out.println("maximum value: "+ Collections.max(set,new MyComparator()).scores);  //最大值

 }

}

class Student{
 int scores;
 public Student(int scores){
  this.scores = scores;
 }
 
}
class MyComparator implements Comparator<Student>{
 @Override
 public int compare(Student o1, Student o2) {// o1>o2 返回1,o1<o2 返回-1 o1=o2 返回0
  return  o2.scores - o1.scores;
 }
 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章