今天我接受了一次采访,我已经给出了两个java类,并要求通过注册号搜索狗的详细信息。我知道Java.util.ArrayList.contains(Object)
,但不知道如何实现有多个字段时。使用比较器在ArrayList中搜索
第二个问题是:在这个例子中可以使用的最有效的搜索技术是什么?我想过Collections.binarySearch
,但不确定它在这个例子中是最有效的。如果是这样,我该如何执行它?
DogSort.java
public class DogSort {
public static void main(String[] args) {
ArrayList<Dog> listDog = new ArrayList<Dog>();
Scanner sc = new Scanner(System.in);
listDog.add(new Dog("Max", "German Shepherd", "33"));
listDog.add(new Dog("Gracie","Rottweiler","11"));
Collections.sort(listDog, Dog.COMPARE_BY_NAME);
System.out.println(listDog);
}
}
Dog.java
class Dog {
private String name;
private String breed;
private String registrationNumber;
public Dog(String name, String breed, String registrationNumber) {
this.name = name;
this.breed = breed;
this.registrationNumber = registrationNumber;
}
public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
public int compare(Dog one, Dog other) {
return one.name.compareTo(other.name);
}
};
//getter and setter methods for all private variable
}
覆盖等于检查DOG类中的注册号相等的方法。 https://stackoverflow.com/questions/8180430/how-to-override-equals-method-in-java –
除非列表按查找字段排序,否则不能使用二分法搜索。 – shmosel
@shmosel雅,那是真的。 – jParmar