实现Comparable接口,进行排序


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;

//构造方法
public Book(String name,float price,String press,String author){
this.name = name;
this.price = price;
this.press = press;
this.author = author;
System.out.println(name.toString());
}
@SuppressWarnings("unchecked")
public static void main(String[] args){
List list = new ArrayList();
Book b1=new Book("java1",25f,"不错的书","LY1");
Book b2=new Book("java2",26f,"不错的书","LY2");
Book b3=new Book("java3",50f,"不错的书","LY3");
Book b4=new Book("java4",20f,"不错的书","LY4");
Book b5=new Book("java5",15f,"不错的书","LY5");
list.add(b1);
list.add(b2);
list.add(b3);
list.add(b4);
list.add(b5);
Collections.sort(list);
for(int i=0;i Book book = (Book)list.get(i);
System.out.println(book);
}
}
//重写
public int compareTo(Object obj) {
Book p = (Book)obj;
if(p.price>this.price){
return 1;
}
else if(p.price return -1;
}
else{
return 0;
}
}
//重写toString方法
public String toString(){//这上是重写了本类的toString方法,对系统自带的其它字段的toString方法无效
return "书名:"+this.name+", 价格:"+this.price+", 说明:"+this.press+", 作者: "+this.author;
}
}
//.sort(List)方法,当然还可能使用java.util.Arrays.sort(数组),那样就必须把//list转化为数组,由于本例使用Collections.sort(List)已经足够,另一方法,大家可//以尝试自已使用.

你可能感兴趣的:(Java)