我使用找到了来自两个不同列表的两个字符串之间的匹配索引
index = Collections.binarySearch(aList, bList);
但是,有多个字符串与aList中的字符串相匹配。我可以使用递减索引以找到bList中的第一个索引匹配
if (index >= 0 ){
while (aList.get(index-1) != bList){
--index;
break;
}
然而,我只能找到第一场比赛。我尝试过的所有代码都不适用于从第一个匹配到最后一个匹配的递增以及输出每个匹配索引中的所有字符串。有办法解决这个问题吗?我真的很感谢你的帮助!
以下是更正并完成的版本:
List<String> aList = List.of("Carrot", "Carrot", "Cauliflower",
"Mushroom", "Mushroom", "Mushroom", "Mushroom", "Pointed cabbage");
String bItem = "Mushroom";
int index = Collections.binarySearch(aList, bItem);
if (index >= 0) {
int firstIndexInclusive = index;
while (firstIndexInclusive > 0 && aList.get(firstIndexInclusive - 1).equals(bItem)) {
firstIndexInclusive--;
}
int lastIndexExclusive = index;
while (lastIndexExclusive < aList.size() && aList.get(lastIndexExclusive).equals(bItem)) {
lastIndexExclusive++;
}
// Print all matching entries
for (int i = firstIndexInclusive; i < lastIndexExclusive; i++) {
System.out.println("" + i + ": " + aList.get(i));
}
} else {
System.out.println("Not found");
}
输出为:
3: Mushroom 4: Mushroom 5: Mushroom 6: Mushroom
您的代码出了什么问题
这条线路有几个问题:
while (aList.get(index-1) != bList){
index
可能是0(迟早(,如果是,aList.get(index-1)
将抛出异常。与!=
进行比较通常不起作用,除非bList
是基元(而不是像对象那样的引用类型((即使在这种情况下,这也不是推荐的可读方式(。
这行也错了:
break;
在递减index
一次后,您将脱离循环,因此,如果左侧有更多匹配项,则不包括它们。
最后,您显示的代码中没有任何内容可以在binarySearch()
返回的索引右侧找到匹配项。