2015年9月30日 星期三

Comparable 的用法

Comparable 的用法:
public class ComparableStudent implements Comparable<ComparableStudent>{
    private String name;
    private long id = 0;
    private double gpa = 0.0;

    public ComparableStudent(String name, long id, double gpa) {
        this.name = name;
        this.id = id;
        this.gpa = gpa;
    }

    public String getName() {
        return name;
    }
        
    @Override
    public int compareTo(ComparableStudent o) {
        int result = this.name.compareTo(o.getName());
        if (result > 0){return 1;}
        else if (result < 0){return -1;}
        else {return 0;}
    }
}

Demo 程式:
import java.util.Set;
import java.util.TreeSet;

public class Demo {
    public static void main(String[] args){
        Set<ComparableStudent> studentList = new TreeSet<>();
        
        studentList.add(new ComparableStudent("Thomas Jefferson", 1111, 3.8));
        studentList.add(new ComparableStudent("John Adams", 2222, 3.9));
        studentList.add(new ComparableStudent("George Washington", 3333, 3.4));
         
         for (ComparableStudent student : studentList){
             System.out.println(student.getName());
         }
    }
}