2016-02-01 26 views
0

我試圖用Collections.binarySearch();Java集合可比錯第三個參數中Collections.binarySearch類型()

我需要相比基礎上,ItemmId領域使用二進制搜索

的編譯錯誤是:

發現 '了java.util.Comparator' 必要「的java.util.Comparator <? super java.lang.comparable <? extends java.lang.comparable <? extends java.lang.comparable <? >>>>」

public class SomeOuterClass { 
public static class Item implements Comparable<Item> { 
    static long id = 0; 
    public Boolean isSaved; 
    public Boolean isLoved; 

    long mId; 
    Post post; 

    public Item(Post p) { 
     mId = id++; 
     post = p; 
     isSaved = Boolean.FALSE; 
     isLoved = Boolean.FALSE; 
    } 

    long getId() { 
     return mId; 
    } 

    @Override 
    public int compareTo(Item o) { 
     return Comparators.ID.compare(this, o); 
    } 


    public static class Comparators { 
     public static Comparator<Item> TITLE = new Comparator<Item>() { 
      @Override 
      public int compare(Item o1, Item o2) { 
       return o1.post.title().compareTo(o2.post.title()); 
      } 
     }; 
     public static Comparator<Item> ID = new Comparator<Item>() { 
      @Override 
      public int compare(Item o1, Item o2) { 
       return (int) (-(o1.mId - o2.mId));//I am putting a minus to indicate list is in descending order 
      } 
     }; 
    } 

} 

private List<Item> items = new ArrayList<Item>(); 

public Item findByBinSrach(int itemId) { 
    int index = Collections.binarySearch(items, itemId, Item.Comparators.ID);//Here it is not recognizing the 3rd parameter 
    return getItem(index); 
}} 
+2

'(int)( - (o1.mId - o2.mId))'最好寫成Long.compare(o2.mId,o1.mId)',以避免溢出和投射。 –

回答

1

第二個參數應該是Item你正在尋找,itemIdCollections.binarySearch無法知道如何將intItem關聯。

您可能會發現更容易items存儲爲LinkedHashMap<Integer, Item>(如果你需要插入順序被保存下來,你可以使用HashMap,如果你不關心順序),其中關鍵是itemId。然後,您可以簡單地使用return items.get(itemId)。其他

兩點:

  1. 它通常是一個壞主意,在構造函數的副作用(在這種情況下,增加id):它使測試(除其他事項外)硬盤。將mId作爲構造函數參數注入會更好;
  2. 製作mId最後,爲了使它不能在製作後更改 - 如果您採用上面的Map建議,這一點尤其重要,因爲您不希望地圖關鍵字與返回的值不同。