package ersatz;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Ersatz {
public static void main(String[] args) {
List list = new LinkedList();
list.add(new Book("a", "aa", 100));
list.add(new Book("b", "bb", 10));
list.add(new Book("c", "cc", 19));
list.add(new Book("d", "dd", 80));
sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Book b1 = (Book) o1;
Book b2 = (Book) o2;
if (b1.getPrice() > b2.getPrice()) {
return 1;
} else if (b1.getPrice() < b2.getPrice()) {
return -1;
} else {
return 0;
}
}
});
for (Object value : list) {
System.out.println(value);
}
sort(list, new Comparator() {
@Override
public int compare(Object b, Object p) {
Book b1 = (Book) b;
Book b2 = (Book) p;
if (b1.getPrice() > b2.getPrice()) {
return -1;
} else if (b1.getPrice() < b2.getPrice()) {
return 1;
} else {
return 0;
}
}
});
for (Object value : list) {
System.out.println(value);
}
}
public static void sort(List list, Comparator comparator) {
int size = list.size();
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - 1 - i; ++j) {
Book b1 = (Book) list.get(j);
Book b2 = (Book) list.get(j + 1);
if (comparator.compare(b1, b2) > 0) {
list.set(j, b2);
list.set(j + 1, b1);
}
}
}
}
}
class Book {
private String name;
private String author;
private double price;
@Override
public String toString() {
return "名稱:" + name + "\t\t價格:" + price + "\t\t作者:" + author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Book(String name, String author, double price) {
this.name = name;
this.author = author;
this.price = price;
}
}