本人刚学java不久今天遇到了一个难题,恳请各位指点。
我想对 对象的价格(price)进行排序,用了Collections.sort匿名内部类进行排序,但是不起作用,代码如下:
package collections_;
import java.util.*;
public class ListExercise02 {
public static void main(String[] args) {
List<Book> myList = new ArrayList<Book>();
myList.add(new Book("红楼梦", 23, "曹雪芹"));
myList.add(new Book("西游记", 25, "吴承恩"));
myList.add(new Book("水浒传", 13, "施耐庵"));
myList.add(new Book("三国", 90, "罗贯中"));
Collections.sort(myList,new Comparator<Book>(){
public int compare(Book b1 , Book b2){
int totalPrice = b1.getPrice() - b2.getPrice();
if(totalPrice > 0){
return 0;
} else if(totalPrice < 0){
return 1;
} else {
return -1;
}
}
});
Iterator<Book> iterator = myList.iterator();
while(iterator.hasNext()) {
Book book = iterator.next();
System.out.println(book);
}
}
}
class Book{
private String name;
private int price;
private String autoor;
public Book(){
}
public Book(String name,int price,String autoor){
this.name = name;
this.price = price;
this.autoor = autoor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAutoor() {
return autoor;
}
public void setAutoor(String autoor) {
this.autoor = autoor;
}
public String toString(){
return "书名:" + name + " 价格:" + price + " 作者:" + autoor;
}
}
//运行结果:
书名:红楼梦 价格:23 作者:曹雪芹
书名:西游记 价格:25 作者:吴承恩
书名:水浒传 价格:13 作者:施耐庵
书名:三国 价格:90 作者:罗贯中
但是如果我使用这样的语句却是可行的 return b1.getPrice() - b2.getPrice();
,请问这是什么原理呢?