简体   繁体   中英

Search in a implementation of LinkedList with Comparator

I have this interface:

class CustomLinkedList<T> {
    public void append(T dado);
    public void addFirst(T dado);
    public T search(Comparator<T> cmp);
    public void printObjects();
}

I need to search in a linked list with a Comparator, but comparators have the compare(obj1, obj2) method with 2 parameters. Here is an example of a comparator:

public class SearchByEmail implements Comparator<Student> {

    public SearchByEmail(String email) {
        // TODO Auto-generated constructor stub
    }

    @Override
    public int compare(Student o1, Student o2) {
        // TODO Auto-generated method stub
        return 0;
    }

}

Anyone have an idea of how to implement search method with the comparator?

An example that is horrible:

public T search(Comparator<T> cmp) {
    Node<T> current = first;

    do {
        if(cmp.compare(current.getElement(), null) == 0){
            return current.getElement();
        }

        current = current.getNext();

    } while (current != null);

    return null;
}

And the SearchByEmail:

public class SearchByEmail implements Comparator<Student> {
    private String email;

    public SearchByEmail(String email) {
        this.email = email;
    }

    @Override
    public int compare(Student o1, Student o2) {
        if(o1.getEmail().equals(email)) return 0;
        return 1;
    }

}

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