我正在制作一个图书索引,其中有一个名为 Entry 的内部类,它包含一个 String (单词本身)和一个 Integer TreeSet 来保存该单词出现的所有行号。
我有一个 ListIndex 类(它包含 Entry 类),我在其中创建了一个 Entry 类型的 ArrayList。当我向列表中添加一个单词时,我需要使用 binarySearch() 检查该单词是否已在列表中。但是,我无法使用 Collections.binarySearch(myList, word),因为 ArrayList 的类型为 Entry。
我的 Entry 类实现了 Comparable,但我仍然不明白如何解决这个问题。任何帮助将不胜感激!
最佳答案
您应该像这样在 Entry
中实现 Comparable
接口(interface)
static class Entry implements Comparable {
String text;
TreeSet<Integer> set;
public Entry(String text, TreeSet<Integer> set) {
this.text = text;
this.set = set;
}
@Override
public String toString() {
return text;
}
@Override
public int compareTo(Object obj) {
if (obj instanceof String)
return text.compareTo((String) obj);
else {
Entry otherEntry = (Entry) obj;
return text.compareTo(otherEntry.text);
}
}
}
public static void main(String[] args) {
List<Entry> entries = new ArrayList<>();
entries.add(new Entry("bbbb", new TreeSet<>()));
entries.add(new Entry("aaaa", new TreeSet<>()));
entries.add(new Entry("cccc", new TreeSet<>()));
entries.add(new Entry("hhhh", new TreeSet<>()));
entries.add(new Entry("dddd", new TreeSet<>()));
Collections.sort(entries);
int index = Collections.binarySearch(entries, "cccc", (e1, e2) -> e1.compareTo(e2));
System.out.println(index);
}
,输出
2
关于java - 如何在 Entry 类上调用 binarySearch() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61621726/