首页 > 代码库 > Java中的Comparable<T>接口

Java中的Comparable<T>接口

在使用普通数组的时候,如果想对数据进行排序,可以调用java.util.Arrays.sort()。但要通过该方式对数组进行排序,还需要数组中的对象实现Comparable<T>接口。

package org.lyk.entities; public class Book implements Comparable<Book>{    static int totalCount;    private String title;    @Override    public String toString()    {        return "Book [title=" + title + ", price=" + price + "]";    }    private float price;         public Book(){}    public Book(String title, float price)    {        super();        this.title = title;        this.price = price;     }          @Override    public int compareTo(Book o)    {//        private String title;//        private float price;//        private String category;//        private Author author;                if(this.price < o.price)            return -1;        else if(this.price > o.price)            return 1;                if(this.title.compareTo(o.title) != 0)            return this.title.compareTo(o.title);                        return 0;    } }

 

package org.lyk.main;import org.lyk.entities.Book;public class Main{     public static void main(String[] args)    {        Book[] books = new Book[]                {                        new Book("Java", 85),                        new Book("Oracle", 99),                        new Book("Html5", 85),                        new Book("JSP", 64),                        new Book("Servlet", 99)                };        java.util.Arrays.sort(books);        for(Book item : books)        {            System.out.println(item);        }                System.out.println(("" instanceof String));    }}

 

Java中的Comparable<T>接口