我得到一個空指針,不熟悉比較方法並試圖找出我要出錯的地方。這個想法是我根據銷售的產品數量進行排序,然後獲得銷售的前5名產品。一旦我實現了比較方法,它將返回一個NullPointer。按對象字段排序列表
public Result index() {
// Get list of all categories in ascending order
String name = "Best Sellers";
List<Category> categoriesList = Category.findAll();
List<Product> productsList;
Long cat = new Long("11");
productsList = bestSellers();
return ok(index.render(env, categoriesList, productsList, cat, "", getCurrentUser(), name));
}
public List<Product> bestSellers(){
List<Product> temp = Product.findAll("");
Collections.sort(temp, new Comparator<Product>() {
@Override
public int compare(Product p1, Product p2) {
if(p1.getCopiesSold()>p2.getCopiesSold()){
return 1;
} else if(p1.getCopiesSold()<p2.getCopiesSold()){
return -1;
}
return 0;
}
});
List<Product> bestSellers = new ArrayList<>();
for(int i=0; i<5; i++){
bestSellers.add(temp.get(i));
}
return bestSellers;
}
我的吸氣劑對有些項目尚未有訂單,讓我不得不增加一個檢查空和一切工作正常返回null。
public Integer getCopiesSold() {
if(copiesSold==null){
copiesSold = 0;
}
return copiesSold;
}
你能發佈錯誤日誌嗎? –
另外,這是什麼意思呢 - > Product.findAll(「」); ? –
您的比較中還存在一個錯誤,否則if應該是 - > else if(p1.getCopiesSold()