/*
自然排序
*/
public class ComparatorTest {
public static void main(String[] args) {
Book[] books = new Book[4];
books[0] = new Book("《如何让富婆爱上我》", 100, 20);
books[1] = new Book("《我的霸道总裁》", 80, 13);
books[2] = new Book("《消失的新娘》", 90, 23);
books[3] = new Book("《我的100个女朋友》", 135, 21);
compare(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (!(o1 instanceof Book) || !(o2 instanceof Book)) {
throw new RuntimeException("类型不匹配!!!");
}
//向下转型
Book b1 = (Book) o1;
Book b2 = (Book) o2;
return b1.price - b2.price;
}
});
System.out.println(Arrays.toString(books));
compare(books, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (!(o1 instanceof Book) || !(o2 instanceof Book)) {
throw new RuntimeException("类型不匹配!!!");
}
//向下转型
Book b1 = (Book) o1;
Book b2 = (Book) o2;
return b1.number - b2.number;
}
});
System.out.println(Arrays.toString(books));
}
public static void compare(Book[] books, Comparator c) {
for (int i = 0; i < books.length - 1; i++) {
for (int j = 0; j < books.length - i - 1; j++) {
if (c.compare(books[j], books[j + 1]) > 0) {
Book temp = books[j];
books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}
}
class Book {
String name;
int price;
int number;
public Book(String name, int price, int number) {
this.name = name;
this.price = price;
this.number = number;
}
@Override
public String toString() {
return name + " " + price + " " + number;
}
}
定制排序
public class ComparableTest {
public static void main(String[] args) {
Book[] books = new Book[4];
books[0] = new Book("《如何让富婆爱上我》", 100, 20);
books[1] = new Book("《我的霸道总裁》", 80, 13);
books[2] = new Book("《消失的新娘》", 90, 23);
books[3] = new Book("《我的100个女朋友》", 135, 21);
compare(books);
System.out.println(Arrays.toString(books));
}
public static void compare(Book[] books) {
for (int i = 0; i < books.length - 1; i++) {
for (int j = 0; j < books.length - i - 1; j++) {
if (books[j].compareTo(books[j + 1]) > 0) {
Book temp = books[j];
books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}
}
class Book implements Comparable {
String name;
int price;
int number;
public Book(String name, int price, int number) {
this.name = name;
this.price = price;
this.number = number;
}
@Override
public String toString() {
return name + " " + price + " " + number;
}
//比较内容,功能
@Override
public int compareTo(Object o) {
if (!(o instanceof Book)) {
throw new TypeMismatchException("类型不匹配!!!");
}
//向下转型
Book b = (Book) o;
//此处定制
return this.price - b.price;
}
}
class TypeMismatchException extends RuntimeException {
public TypeMismatchException() {
}
public TypeMismatchException(String message) {
super(message);
}
}