我得到一个空指针,不熟悉比较方法并试图找出我要出错的地方。这个想法是我根据销售的产品数量进行排序,然后获得销售的前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()