简体   繁体   中英

Error trying to binarySearch with my own comparator

I'm trying to create a class where I can insert objects quickly into a class list with the help of binary search.

Here's my class and inner class:

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");
        }
    }
}

The inner class is made for comparing the objects of list so that Collections.binarySearch can work. However, I'm getting this error. What does it mean, and what do I do about it?

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 {
    ...
}

implements "raw" Comparator interface, which accepts Object parameters, ie compare(Object,Object) . However, this is not what you want to override, because your comparator is specific to PostingsEntry .

Therefore, you need to implement Comparator<PostingsEntry> :

class PostingsEntryComparator implements Comparator<PostingsEntry> {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM