標題:
自訂排序 (一)
[打印本頁]
作者:
tonyh
時間:
2021-11-8 17:38
標題:
自訂排序 (一)
本帖最後由 tonyh 於 2022-11-25 17:58 編輯
試定義一集合,集合中包含五個 Student 物件,再透過實作 Comparator 介面自訂比較器,分別完成「依分數遞減排序」及「依座號遞增排序」的比較方法,以 Collections 類別下的 sort() 方法搭配自訂的比較器,分別完成「依分數遞減排序」及「依座號遞增排序」之操作練習。
[attach]14393[/attach]
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Ch01 {
ArrayList<Student> stu=new ArrayList<Student>();
Ch01()
{
stu.add(new Student(4, "大雄", 60));
stu.add(new Student(1, "小叮噹", 90));
stu.add(new Student(3, "宜靜", 100));
stu.add(new Student(2, "阿福", 70));
stu.add(new Student(5, "技安", 20));
System.out.println("原始資料:");
show();
Collections.sort(stu, new MyComparator1()); //使用自定比較器來排序
System.out.println("依座號遞增排序:");
show();
Collections.sort(stu, new MyComparator2());
System.out.println("依分數遞減排序:");
show();
}
void show()
{
System.out.println("座號\t姓名\t分數");
System.out.println("-------------------");
for(int i=0; i<stu.size(); i++)
System.out.println(stu.get(i).num+"\t"+stu.get(i).name+"\t"+stu.get(i).score);
System.out.println();
}
class MyComparator1 implements Comparator<Student>
{
@Override
public int compare(Student o1, Student o2) { //遞增的比較方法
return o1.num-o2.num;
}
}
class MyComparator2 implements Comparator<Student>
{
@Override
public int compare(Student o1, Student o2) { //遞減的比較方法
return o2.score-o1.score;
}
}
class Student //內部類別
{
int num, score;
String name;
Student(int n, String m, int s)
{
num=n;
name=m;
score=s;
}
}
public static void main(String[] args) {
new Ch01();
}
}
複製代碼
作者:
駱顗安
時間:
2021-11-8 19:04
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class P1 {
ArrayList<Student> stu=new ArrayList<P1.Student>();
P1(){
stu.add(new Student(4, "大雄", 60));
stu.add(new Student(1, "小叮噹", 90));
stu.add(new Student(3, "宜靜", 100));
stu.add(new Student(2, "阿福", 70));
stu.add(new Student(5, "技安", 20));
System.out.println("原始資料:");
show();
Collections.sort(stu, new MyComprator1());
System.out.println("依座號遞增排序:");
show();
Collections.sort(stu, new MyComprator2());
System.out.println("依分數遞減排序:");
show();
}
void show(){
System.out.println("座號\t姓名\t分數");
System.out.println("-------------------");
for(Student s:stu){
System.out.println(s.num+"\t"+s.name+"\t"+s.score);
}
}
class Student{
int num,score;
String name;
Student(int n,String m,int s) {
num=n;
name=m;
score=s;
}
}
class MyComprator1 implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.num-o2.num;
}
}
class MyComprator2 implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o2.score-o1.score;
}
}
public static void main(String[] args) {
new P1();
}
}
複製代碼
歡迎光臨 種子論壇 | 高雄市資訊培育協會學員討論區 (http://istak.org.tw/seed/)
Powered by Discuz! 7.2