Comparable接口比较排序 示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Comparable接口比较排序 示例相关的知识,希望对你有一定的参考价值。

package cn.caijiajia.campaignnew.job;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Book implements Comparable{
/*编写一个类Book,具有name,price,press,author属性.然后创建5个对象放入ArrayList中,并实现按照price大小排序(使用Comparable接口排序),
然后遍历ArrayList输出每个Book对象。*/
private String name;
private float price;
private String press;
private String author;
private int id;

//构造方法
public Book(String name,float price,String press,String author,int id){
this.name = name;
this.price = price;
this.press = press;
this.author = author;
this.id = id;
System.out.println(name.toString());
}
@SuppressWarnings("unchecked")
public static void main(String[] args){
List<Book> list = new ArrayList<Book>();
Book b1=new Book("java1",25f,"不错的书","LY1",1);
Book b2=new Book("java2",30f,"不错的书","LY2",2);
Book b3=new Book("java3",30f,"不错的书","LY2",3);
Book b4=new Book("java4",30f,"不错的书","LY2",4);
Book b5=new Book("java5",80f,"不错的书","LY3",5);
Book b6=new Book("java6",40f,"不错的书","LY4",6);
Book b7=new Book("java7",15f,"不错的书","LY5",7);
list.add(b1);
list.add(b2);
list.add(b3);
list.add(b4);
list.add(b5);
list.add(b6);
list.add(b7);

//.sort(List)方法,当然还可能使用java.util.Arrays.sort(数组),那样就必须把
//list转化为数组,由于本例使用Collections.sort(List)已经足够,另一方法,大家可//以尝试自已使用.

Collections.sort(list);
        for(int i=0;i<list.size();i++){
Book book = (Book)list.get(i);
System.out.println(book);
}
}
//重写Comparable接口方法
public int compareTo(Object obj) {
Book p = (Book)obj;
//按价格降序
if(p.price>this.price){
return 1;
}
else if(p.price<this.price){
return -1;
}
else{
//价格相同按id降序(默认是升序)
if(p.id<this.id)
return -1;
else if(p.id>this.id)
return 1;
else
return 0;
}
}
//重写toString方法
public String toString(){//这上是重写了本类的toString方法,对系统自带的其它字段的toString方法无效
return "书名:"+this.name+", 价格:"+this.price+", 说明:"+this.press+", 作者: "+this.author+", id: "+this.id;
}
}

以上是关于Comparable接口比较排序 示例的主要内容,如果未能解决你的问题,请参考以下文章

Comparable接口与Comparator接口的比较————Comparable接口详解

Comparator接口Comparable接口 排序接口的使用方式

数组对象排序:Comparable和Comparator

转载Java中Comparable和Comparator比较

Map进行排序 用Comparable

java lang(Comparable接口) 和java util(Comparator接口)分析比较