接口应用:内部比较器Comparable
public interface Comparable {public int compareTo(Object obj);
}
public class Book implements Comparable{private String bookName;private String author;private String publisher;private double price;@Overridepublic int compareTo(Object obj) {Book other = (Book)obj;if (this.price>other.price){return 1;}else if (this.price< other.price){return -1;}else {return 0;}}public Book(){}public Book(String bookName,String author,String publisher,double price){this.bookName = bookName;this.author = author;this.publisher = publisher;this.price = price;}
}
public class Person implements Comparable{private String name;private int age;public Person(){}public Person(String name,int age){this.name = name;this.age = age;}@Overridepublic int compareTo(Object obj) {Person other = (Person) obj;return this.age- other.age;}
}
public class Test {public static void main(String[] args) {Book book1 = new Book("倚天屠龙记","金庸","清华大学出版社",35);Book book2 = new Book("倚天屠龙记","金庸","清华大学出版社",31);int result = book1.compareTo(book2);System.out.println(result);Person person1 = new Person("张三",24);Person person2 = new Person("李四",24);result = person1.compareTo(person2);System.out.println(result);}
}
运行结果如下: