昨日、テクニカルラウンドに実装するタスクが次のように与えられました。私はあなたがすべてのタスクを実装することを望んでいない、私は自分自身を試みたが、私は質問3で立ち往生した。私の質問はどのように登録番号で検索するために実装するのですか?質問5によれば、より効率的でなければならないからです。私はHashMapを試しましたが、解決できませんでした。複数の引数でArrayListを検索する
- 犬のリストをアルファベット順に、名前をつけて、次に繁殖させて管理します。
- 新しい犬を追加する方法を提供します。
- 登録番号で検索する方法を提供します。
- 名前で検索する方法を提供します。
- 利用可能な最も効率的な検索手法を採用しています。
- 犬の初期リストを受け入れるコンストラクターです。 シンプルな構築物がDogクラスを改善するために何ができるか
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