#java #string #arraylist #binary-search
Вопрос:
Как я могу использовать двоичный поиск с ArrayList?
Вот элементы списка ArrayList:
public class DictionaryElements implements
Comparable<DictionaryElements>, Comparator<DictionaryElements>{
private String word;
private String translation;
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getTranslation() {
return translation;
}
public void setTranslation(String translation) {
this.translation = translation;
}
public DictionaryElements() {
}
public DictionaryElements(String word, String translation) {
this.word = word;
this.translation = translation;
}
@Override
public String toString() {
return word " - " translation;
}
@Override
public int compareTo(DictionaryElements dictionary) {
return this.word.compareTo(dictionary.word);
}
@Override
public int compare(DictionaryElements wordOne, DictionaryElements wordTwo) {
return wordOne.getWord().compareTo(wordTwo.getWord());
}
}
Чем я отсортировал список здесь:
public class DictionarySorter {
ArrayList<DictionaryElements> dictionaryList = new ArrayList<>();
public DictionarySorter(ArrayList<DictionaryElements> dictionaryList) {
this.dictionaryList = dictionaryList;
}
public ArrayList<DictionaryElements> getSortedByWord() {
Collections.sort(dictionaryList);
return dictionaryList;
}
}
И здесь я попытался подразумевать Двоичный поиск:
public class Main {
public static void main(String[] args) {
DictionaryElements dictionaryElements = new DictionaryElements();
ArrayList<DictionaryElements> dictionaryList = new ArrayList<>();
DictionarySorter dictionarySorter = new
DictionarySorter(dictionaryList);
boolean found = true;
dictionaryList();
Scanner scanner = new Scanner(System.in);
System.out.println("Write one word in English:");
String wordInEnglish = scanner.nextLine();
int index = Collections.binarySearch(dictionaryList, wordInEnglish);
if (found) {
//code here.
}
else {
System.out.println("Sorry, i didn't find " wordInEnglish " ;(");
}
scanner.close();
}
public static void dictionaryList() {
ArrayList<DictionaryElements> dictionaryList = new ArrayList<>();
dictionaryList.add(new DictionaryElements("Apple", "Apfel"));
dictionaryList.add(new DictionaryElements("Pear", "Birne"));
dictionaryList.add(new DictionaryElements("Orange", "Orange"));
DictionarySorter dictionarySorter = new DictionarySorter(dictionaryList);
ArrayList<DictionaryElements> sortedDictionaryList = dictionarySorter.getSortedByWord();
for (DictionaryElements dictionary : sortedDictionaryList) {
System.out.println(dictionary);
}
}
}
Ошибка говорит:
Метод BinarySearch(Список расширяет Сопоставимые супер T>>>, T) в коллекциях типов неприменимо для аргументов (ArrayList, строка)>>
Что я пропустил и как я могу это исправить?
Комментарии:
1. Т — это а
DictionaryElement
, а не аString
Ответ №1:
Если вы посмотрите на объявление метода для Collections.BinarySearch, реализованный компаратор должен быть того же типа, что и передаваемый ключ.
Ваши словарные элементы расширяют сопоставимый тип словарных элементов, но ключ, который вы передаете, имеет тип String.
Вместо этого вам нужно будет передать элемент словаря в качестве ключа:
DictionaryElements key = new DictionaryElements(wordInEnglish, translation);
int index = Collections.binarySearch(dictionaryList, key);
Ответ №2:
У вас есть список DictionaryElements
объектов, и вы ищете строку.
Это все равно, что я протягиваю тебе пакет с яблоками и прошу: эй, найди мне эту грушу.
Компилятор помогает вам и мешает вам писать этот код, так как это не имеет смысла.
Комментарии:
1. Так есть ли какой-нибудь способ это исправить? Пожалуйста, подкрепите свой ответ примерами. Спасибо.