1. 程式人生 > >實現Comparable介面,把物件按優先順序進行排序

實現Comparable介面,把物件按優先順序進行排序

在讀《efficitive java》第12條:考慮實現Comparable介面

使用Comparable介面按物件按屬性的優先順序排序還是比較方便的
例項程式碼

package com.ctc.basic;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Student implements Comparable<Student> {

    private int number;

    private String name;

    private
float score; public Student(int number, String name, float score) { this.number = number; this.name = name; this.score = score; } //排序優先順序number-name-score @Override public int compareTo(Student c) { // 如果number不等按number排序(增序 if (this.number != c.number) { return
this.number > c.number ? 1 : -1; } else { // 如果number和name都相等按score排序(降序) if (this.name.equals(c.name)) { return this.score < c.score ? 1 : -1; } // 如果number相等按name排序(增序) return this.name.compareTo(c.name) > 0 ? 1
: -1; } } @Override public String toString() { return "Student [number=" + number + ", name=" + name + ", score=" + score + "]"; } public static void main(String[] args) { List<Student> students = new ArrayList<Student>() { { add(new Student(1, "a", 2)); add(new Student(3, "a", 3)); add(new Student(7, "a", 5)); add(new Student(5, "a", 2)); add(new Student(3, "a", 2)); add(new Student(7, "c", 2)); add(new Student(1, "b", 5)); add(new Student(7, "a", 2)); add(new Student(7, "c", 10)); } }; Collections.sort(students); for (Student student : students) { System.out.println(student); } } }

輸出結果為

Student [number=1, name=a, score=2.0]
Student [number=1, name=b, score=5.0]
Student [number=3, name=a, score=3.0]
Student [number=3, name=a, score=2.0]
Student [number=5, name=a, score=2.0]
Student [number=7, name=a, score=5.0]
Student [number=7, name=a, score=2.0]
Student [number=7, name=c, score=10.0]
Student [number=7, name=c, score=2.0]