2015年9月30日 星期三

Comparator 的用法

Comparator 的用法:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorDemo {
    public static void main(String[] args){
    
        List<Student> studentList = new ArrayList<>(3);
        Comparator<Student> sortName = new StudentSortName();
        Comparator<Student> sortGpa = new StudentSortGpa();
        
        studentList.add(new Student("Thomas Jefferson", 1111, 3.8));
        studentList.add(new Student("John Adams", 2222, 3.9));
        studentList.add(new Student("George Washington", 3333, 3.4));
        
        Collections.sort(studentList, sortName);
        for (Student student : studentList){
            System.out.println(student.getName());
        }
         Collections.sort(studentList, sortGpa);
        for (Student student : studentList){
            System.out.println(student.getGpa());
        }
    }
}

public class Student {
private String name;
    private long id = 0;
    private double gpa = 0;
            
    public Student(String name, long id, double gpa) {
        this.name = name;
        this.id = id;
        this.gpa = gpa;
    }

    public String getName() {
        return name;
    }

    public double getGpa() {
        return gpa;
    }
}

import java.util.Comparator;

public class StudentSortName implements Comparator<Student> {

    public StudentSortName() {
    }

    @Override
    public int compare(Student o1, Student o2) {
        int result = o1.getName().compareTo(o2.getName());
        if (result != 0){return result;}
        else { return 0;}
    }
}

import java.util.Comparator;

public class StudentSortGpa implements Comparator<Student> {

    public StudentSortGpa() {
    }

    @Override
    public int compare(Student o1, Student o2) {
        if (o1.getGpa() < o2.getGpa()){return 1;}
        else if (o1.getGpa() > o2.getGpa()){ return -1;}
        else {return 0;}
    }
}