栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在对象中实现二进制搜索

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在对象中实现二进制搜索

Java教程的对象排序文章中有一个示例,您可以编写自己的示例

Comparator
以对自定义类型进行比较。

然后,

ArrayList
(或任何其他
List
),要查找的键以及
Comparator
可以一起传递到
Collections.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(20, "B"));    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.    int index = Collections.binarySearch(l, new User(20, null), c);    System.out.println(index);    // Output: 1    index = Collections.binarySearch(l, new User(10, null), c);    System.out.println(index);    // Output: 0    index = Collections.binarySearch(l, new User(42, null), c);    System.out.println(index);    // Output: -4 // See javadoc for meaning of return value.  }}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);  }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/483315.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号