import java.awt.print.Book;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class Col {
public static void main(String[] args) {
List<B> list = new ArrayList<B>();
B b1 = new B(1,"zengxiaohui",11.0,new Date());
B b2 = new B(2,"zengxiaohu2",12.0,new Date());
B b3 = new B(3,"zengxiaohu3",13.0,new Date());
list.add(b3);
list.add(b1);
list.add(b2);
System.out.println("数组序列中的元素:");
myprint(list);
Collections.sort(list); // 根据价格排序
System.out.println("按B中的list方式排序:");
myprint(list);
Collections.sort(list, new PriceComparator()); // 根据价格排序
System.out.println("按书的价格排序:");
myprint(list);
Collections.sort(list, new CalendarComparator()); // 根据时间排序
System.out.println("按书的出版时间排序:");
myprint(list);
Collections.sort(list,new Comparator<B>(){
public int compare(B p1, B p2) {
return new Double(p1.getPrice()).compareTo(new Double(p2.getPrice()));
}
});
System.out.println("代码中的没有累的排序:");
myprint(list);
}
// 自定义比较器:按书的价格排序
static class PriceComparator implements Comparator {
public int compare(Object object1, Object object2) {// 实现接口中的方法
B p1 = (B) object1; // 强制转换
B p2 = (B) object2;
return new Double(p1.getPrice()).compareTo(new Double(p2.getPrice()));
}
}
// 自定义比较器:按书出版时间来排序
static class CalendarComparator implements Comparator {
public int compare(Object object1, Object object2) {// 实现接口中的方法
B p1 = (B) object1; // 强制转换
B p2 = (B) object2;
return p2.getCalendar().compareTo(p1.getCalendar());
}
}
// 自定义方法:分行打印输出list中的元素
public static void myprint(List<B> list) {
Iterator it = list.iterator(); // 得到迭代器,用于遍历list中的所有元素
while (it.hasNext()) {// 如果迭代器中有元素,则返回true
System.out.println("\t" + it.next().toString());// 显示该元素
}
}
}
class B implements Comparable<B>{
private int id;
private String name;
private Double price;
private Date calendar;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Date getCalendar() {
return calendar;
}
public void setCalendar(Date calendar) {
this.calendar = calendar;
}
public B(int id, String name, Double price, Date calendar) {
super();
this.id = id;
this.name = name;
this.price = price;
this.calendar = calendar;
}
@Override
public String toString() {
return "B [id=" + id + ", name=" + name + ", price=" + price + ", calendar=" + calendar + "]";
}
@Override
public int compareTo(B o) {
return new Double(this.getPrice()).compareTo(new Double(o.getPrice()));
}
}
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦