今天我接受了一次採訪,我已經給出了兩個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