0
我試圖用Collections.binarySearch();
Java集合可比錯第三個參數中Collections.binarySearch類型()
我需要相比基礎上,Item
的mId
領域使用二進制搜索。
的編譯錯誤是:
發現 '了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);
}}
'(int)( - (o1.mId - o2.mId))'最好寫成Long.compare(o2.mId,o1.mId)',以避免溢出和投射。 –