当前位置: 代码迷 >> Java相关 >> java List<>排序有关问题
  详细解决方案

java List<>排序有关问题

热度:2234   发布时间:2013-02-25 21:50:16.0
java List<>排序问题
给出一个乱序的list<Seat>,Seat里面有int类型的rowNum(排号)和line座位号,怎么得到先排好序的(先比较rowNum,相同则比较 line 从小到大)的list?

------解决方案--------------------------------------------------------
Java code
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  13  12  43  2进行排序......1  12  43  13  2*/
  相关解决方案