public class Book implements Comparable<Book> {
private Integer id;
private String name;
private double price;
public Book() {
}
public Book(Integer id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
//只要书名一致,返回true
public boolean equals(Object o) {
String myBook = this.getName();
Book b = (Book) o;
String itBook = b.getName();
return myBook.equals(itBook);
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
@Override
public int compareTo(Book o) {
return (int) (this.getPrice() - o.getPrice());
}
}
public class Text {
public static void a() {
LinkedList<Book> list = new LinkedList<>();
Book b1 = new Book(1, "三国演义", 45.5);
Book b2 = new Book(2, "红楼梦", 65.5);
Book b3 = new Book(3, "西游记", 75.5);
Book b4 = new Book(4, "水浒传", 25.5);
Book b5 = new Book(5, "三体", 65);
Book b6 = new Book(6, "java", 15.5);
list.add(b1);
list.add(b2);
list.add(b3);
list.add(b4);
list.add(b5);
list.add(b6);
Collections.sort(list);//对集合进行排序
Book b = new Book();
b.setName("三国演义");
int index = list.indexOf(b);
// System.out.println(index);
//找出比三国演义index小的图书
for (int i = 0; i < index; i++) {
System.out.println(list.get(i));
}
}
public static void main(String[] args) {
a();
}
}