2017-04-13 111 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()方法 –