日期:2014-05-20 浏览次数:20646 次
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Seat { private int rowNumber; private int line; public Seat(int rowNumber, int line) { this.rowNumber = rowNumber; this.line = line; } public int getRowNumber() { return rowNumber; } public void setRowNumber(int rowNumber) { this.rowNumber = rowNumber; } public int getLine() { return line; } public void setLine(int line) { this.line = line; } @Override public String toString() { return rowNumber + " " + line; } } //比较规则 class SeatComparator implements Comparator<Seat> { public int compare(Seat o1, Seat o2) { return (o1.getRowNumber() < o2.getRowNumber() ? -1 : (o1.getRowNumber()> o2.getRowNumber() ? 1: ( o1.getLine() < o2.getLine() ? -1 : (o1.getLine()> o2.getLine() ? 1 :0 )))); } } public class TestSeat { public static void main(String[] args) { Seat s1 = new Seat(1, 1); Seat s2 = new Seat(3, 1); Seat s3 = new Seat(2, 4); Seat s4 = new Seat(3, 2); List<Seat> seats = new ArrayList<Seat>(); seats.add(s1); seats.add(s2); seats.add(s3); seats.add(s4); System.out.println("原始数据:"); for (Seat seat : seats) { System.out.println(seat); } System.out.println("进行排序......"); SeatComparator seatComparator = new SeatComparator(); Collections.sort(seats, seatComparator); for (Seat seat : seats) { System.out.println(seat); } } } /* 原始数据: 1 1 3 1 2 4 3 2 进行排序...... 1 1 2 4 3 1 3 2 */