我正在尝试创建一个类,在其中我可以借助二进制搜索将对象快速插入到类列表中。
这是我的类和内部类:
public class PostingsList implements Iterator<PostingsEntry>{
/** The postings list */
private ArrayList<PostingsEntry> list = new ArrayList<PostingsEntry>();
class PostingsEntryComparator implements Comparator{
@Override
public int compare(PostingsEntry pA, PostingsEntry pB){
if(pA.docID < pB.docID){
return -1;
}
else if(pA.docID == pB.docID){
return 0;
}
else{
return 1;
}
}
}
public void add(PostingsEntry newPostingsEntry){
//put in the right place
PostingsEntryComparator pc = new PostingsEntryComparator();
int res = Collections.binarySearch(list, newPostingsEntry, pc);
if(res < 0){
list.add(-res-1, newPostingsEntry);
}
else{
System.out.println("already exists");
}
}
}
内部类用于比较 list
的对象,以便 Collections.binarySearch
可以工作。但是,我收到此错误。这是什么意思,我该怎么办?
n180-p69:new sahandzarrinkoub$ sh compile_all.sh
ir/PostingsList.java:22: error: PostingsList.PostingsEntryComparator is not abstract and does not override abstract method compare(Object,Object) in Comparator
class PostingsEntryComparator implements Comparator{
^
ir/PostingsList.java:23: error: method does not override or implement a method from a supertype
@Override
^
2 errors
最佳答案
class PostingsEntryComparator implements Comparator {
...
}
实现“原始”Comparator
接口(interface),它接受 Object
参数,即 compare(Object,Object)
.但是,这不是您要覆盖的内容,因为您的比较器特定于 PostingsEntry
.
因此,你需要实现Comparator<PostingsEntry>
:
class PostingsEntryComparator implements Comparator<PostingsEntry> {
...
}
关于java - 尝试使用我自己的比较器进行 binarySearch 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48598044/