我有这个界面:
class CustomLinkedList<T> {
public void append(T dado);
public void addFirst(T dado);
public T search(Comparator<T> cmp);
public void printObjects();
}
我需要使用比较器在链表中进行搜索,但比较器使用2个参数的比较(obj1,obj2)方法。以下是比较器的示例:
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;
}
}
任何人都知道如何使用比较器实现搜索方法?
答案 0 :(得分:0)
一个可怕的例子:
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;
}
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;
}
}