1
昨天,我在技術回合中得到了以下任務。我不希望你執行所有的任務,我嘗試過自己,但我堅持問題3.我的問題是我如何實現通過註冊號搜索?因爲按照問題5,它應該更有效率。我嘗試了HashMap,但無法解決它。在具有多個參數的ArrayList中搜索
- 按字母順序維護一個名單,首先是名字,然後是品種。
- 提供添加新狗的方法。
- 提供按註冊號碼進行搜索的方法。
- 提供按名稱搜索的方法。
- 採用最有效的搜索技術。
- 構造函數接受狗的初始列表。
- 可以做什麼簡單的結構來提高狗類
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"));
listDog.add(new Dog("Sam", "Beagle", "22"));
System.out.println(listDog);
System.out.println("Select one of the following commands: ");
System.out.println(
"Press 1: Sort by name\n"+
"Press 2: Sort by breed\n" +
"Press 3: Add new dog\n" +
"Press 4: Search by registration number\n" +
"Press 5: Serach by Name\n ");
int i = sc.nextInt();
switch (i){
case 1: Collections.sort(listDog, Dog.COMPARE_BY_NAME);
System.out.println(listDog);
break;
case 2:
Collections.sort(listDog, Dog.COMPARE_BY_BREED);
System.out.println(listDog);
break;
default:
System.out.println("Invalid input");
break;
}
}
}
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 String getName() {
return this.name;
}
public String getBreed() {
return this.breed;
}
public String getRegistrationNumber() {
return this.registrationNumber;
}
public void setName(String name) {
this.name = name;
}
public void setBreed(String breed) {
this.breed = breed;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
@Override
public String toString() {
return this.name;
}
public static Comparator<Dog> COMPARE_BY_NAME = new Comparator<Dog>() {
public int compare(Dog one, Dog other) {
return one.name.compareTo(other.name);
}
};
public static Comparator<Dog> COMPARE_BY_BREED = new Comparator<Dog>() {
public int compare(Dog one, Dog other) {
return one.breed.compareTo(other.breed);
}
};
}
'HashMap'是正確的方向。你嘗試了什麼,什麼不起作用? – Thomas
@Thomas我有代碼,但不知道如何顯示代碼?我無法進入答案部分。 – jParmar
請將其編輯爲您的問題。 – Thomas