使用Comparator进行Java排序对象

时间:2014-11-02 18:21:29

标签: java

您好我想我已经学会了如何使用Comparator对Java对象进行排序,请查看下面的代码,看看我是否在正确的轨道上

public class Books{

    private String bookName;
    private String bookDesc;
    private int quantity;

    public Books(String bookName, String bookDesc, int quantity) {
        super();
        this.bookName = bookName;
        this.bookDesc = bookDesc;
        this.quantity = quantity;
    }

    public String getbookName() {
        return bookName;
    }
    public void setbookName(String bookName) {
        this.bookName = bookName;
    }
    public String getbookDesc() {
        return bookDesc;
    }
    public void setbookDesc(String bookDesc) {
        this.bookDesc = bookDesc;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}

1 个答案:

答案 0 :(得分:0)

如果您尝试根据图书名称对图书清单进行排序,请尝试此操作:

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class Books implements Comparator<Books>{

private String bookName;
private String bookDesc;
private int quantity;

public Books(String bookName, String bookDesc, int quantity) {
    super();
    this.bookName = bookName;
    this.bookDesc = bookDesc;
    this.quantity = quantity;
}

@Override
public String toString() {
    return bookName+","+bookDesc+","+quantity;
}

public String getbookName() {
    return bookName;
}
public void setbookName(String bookName) {
    this.bookName = bookName;
}
public String getbookDesc() {
    return bookDesc;
}
public void setbookDesc(String bookDesc) {
    this.bookDesc = bookDesc;
}
public int getQuantity() {
    return quantity;
}
public void setQuantity(int quantity) {
    this.quantity = quantity;
}

@Override
public int compare(Books b1, Books b2) {

    return b1.getbookName().compareTo(b2.getbookName());
}

public static void main(String[] args) {

    Books b1=new Books("Here You Go", "General", 10);
    Books b2=new Books("R You There", "General", 20);

    List<Books>list=new LinkedList<Books>();
    list.add(b2);
    list.add(b1);

    System.out.println(list);//unsorted

    Collections.sort(list, b1);//passing list and Comparator to the sort() method
    //since Books implements Comparator interface any Books object "IS-A" Comparator.
    System.out.println(list);//sorted

}

}