当前位置: 首页 > 面试题库 >

Java集合binarySearch无法正常工作

邓昀
2023-03-14
问题内容

我只是想使用本机Java binarySearch,希望它总是可以找到第一个匹配项。但是它并不总是返回第一次出现的错误,我在这里做错了什么?

import java.util.*;

class BinarySearchWithComparator
{
  public static void main(String[] args)
  {
    // Please scroll down to see 'User' class implementation.
    List<User> l = new ArrayList<User>();
    l.add(new User(10, "A"));
    l.add(new User(10, "A"));
    l.add(new User(10, "A"));

    l.add(new User(20, "B"));
    l.add(new User(20, "B"));
    l.add(new User(20, "B"));
    l.add(new User(20, "B"));
    l.add(new User(20, "B"));
    l.add(new User(20, "B"));
    l.add(new User(20, "B"));


    l.add(new User(30, "C"));
    l.add(new User(30, "C"));
    l.add(new User(30, "C"));
    l.add(new User(30, "C"));

    Comparator<User> c = new Comparator<User>() {
      public int compare(User u1, User u2) {
        return u1.getId().compareTo(u2.getId());
      }
    };

    // Must pass in an object of type 'User' as the key.
    // The key is an 'User' with the 'id' which is been searched for.
    // The 'name' field is not used in the comparison for the binary search,
    // so it can be a dummy value -- here it is omitted with a null.
    //
    // Also note that the List must be sorted before running binarySearch,
    // in this case, the list is already sorted.
    Collections.sort(l,c);

    int index = Collections.binarySearch(l, new User(10, null), c);
    System.out.println(index);

    index = Collections.binarySearch(l, new User(20, null), c);
    System.out.println(index);

    index = Collections.binarySearch(l, new User(30, null), c);
    System.out.println(index);

    index = Collections.binarySearch(l, new User(42, null), c);
    System.out.println(index);
  }
}

class User {
  private int id;
  private String name;

  public User(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public Integer getId() {
    return Integer.valueOf(id);
  }
}

========

Result:
2 //not 0 ?
6 //not 3?
10 //ok
-15  ok

Why first 10 is not index 0 ?
Why first 20 is not index 3 ?
OK , 30 first occurrence is index 10

=====================================

更新资料

现在看来,API并没有保证!谁能给我一个有关如何找到给定元素的第一个出现和最后一个出现的工作示例(例如User(10,null)?

非常感谢。


问题答案:

Java不保证它将返回相等元素中的哪个元素。当您在相等范围内有多个元素时,您需要向下移动列表以查找与您要查找的元素相等的第一个元素,如下所示:

User lookFor = new User(30, null);
index = Collections.binarySearch(l, lookFor, c);
while (index > 0 && c.compare(lookFor, l[index-1]) == 0) {
    index--;
}
// At this point the index is at the first element of the equal range

您可以将此逻辑包装在静态函数中,以避免每次都编写显式循环。

请注意,如果您的集合是随机访问,这将导致最坏情况下的性能(当有许多相同的元素时)从O(lg(n))降为O(n)。



 类似资料:
  • 问题内容: 我有一个包含一些字段的JPanel。JPanel的高度是有限的,因此我必须在其周围放置一个JScrollPane以便人们向下滚动。 如下所示,它完美显示。但是您无法向下(或向上)滚动。 详细信息面板: 问题答案: 您的DetailPanel没有与之关联的布局管理器,这意味着在您向其添加子项时它不会扩展,这意味着JScrollPane没有任何可滚动的地方。调用DetailPanel或重写

  • 问题内容: 这是我的代码。 这应该返回,但实际上正在返回。为什么这不起作用? 问题答案: 不支持正则表达式,请使用:

  • 问题内容: 这真让我抓狂。我在具有以下结构的文件夹中有一个NetBeans项目: 在src中,我的代码在软件包中。我想做的是使用 来自com.my.package包中的类,但它只是拒绝工作!“ new.png”图像位于资源文件夹中。我在这里想念什么吗? 经过大量的游玩并四处移动“ new.png”图像以查看何时可以找到该图像,它终于可以工作了,但仅当我将图像放入build文件夹时才可以。那么,我该

  • 问题内容: 对于这个愚蠢的问题,我感到抱歉,我一直在搜索如何在我的ArrayList中使用binarysearch,如下所示: 问题是当我使用时: indeks的值始终为-5,我认为应该为2,因为在反转myArrList之后,输出看起来像这样: 那么,在这里我该怎么做才能获得7的正确债款?提前致谢 问题答案: 期望元素按升序排列: 在进行此调用之前,必须根据列表元素的自然顺序将其按升序排序(例如通

  • 问题内容: 考虑以下方法,该方法将返回一个字段(如果存在)或递归调用自身直到找到该字段: 虽然这可行,但我想可以将其缩短为: 但是奇怪的是,该部分似乎总是被调用。 我在这里想念什么? 问题答案: 方法的参数始终在调用方法之前进行求值。您想要带一个仅在不存在时才被调用的:

  • 问题内容: 因此,我的设置无法按我想要的方式工作。因此,每当我运行该程序时,它就会立即从0变为100。我尝试使用,任务,并尝试了,但没有任何尝试。 这是我的程序: @MadProgrammer这是我尝试做一名摆动工作人员并将每个名称写入文档并更新进度栏的尝试。该程序将达到86%左右并停止运行,永远不会创建完成的文档。该程序将创建一个空白文档。这是我首先创建的SwingWorker对象,这是两种方法