2017-04-13 110 views
0

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

你能发布错误日志吗? –

+0

另外,这是什么意思呢 - > Product.findAll(“”); ? –

+0

您的比较中还存在一个错误,否则if应该是 - > else if(p1.getCopiesSold()

回答

1

检查您的方法findAll()。看起来它正在给出一个列表,其中某些值的值为null。当您的比较方法由Collectionsp1.getCopiesSoldp2.getCopiesSold使用的排序算法调用时,会出现错误,因为p1或p2为空。

也有可能该方法是findAll()返回null而不是List,或者方法getCopiesSold返回null。

在java中,某些东西可以具有null值而不会抛出异常,它只会在您尝试调用某个方法或对其执行操作时抛出异常。因此,null变量可以是引发错误的行所使用的任何变量。

+0

谢谢,我在吸气剂中解决了这个问题,但它并没有给我销售的前5名产品。我想扭转列表的顺序? – Lee

+0

@OusmaneMahyDiaw我刚更新它,这是问题,但我想扭转列表的顺序,我正在查看反向API调用。它是否相似? – Lee

+0

@Lee使用Collections.Reverse()方法 –