如何使用二进制搜索打印两个不同 ArrayList 中匹配索引的所有字符串?

How do I print all strings from matching indexes in two different ArrayLists using Binary Search?

我使用以下方法找到了来自两个不同列表的两个字符串之间的匹配索引:

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() 返回的索引右侧的匹配项。