<DiversityScoreMapping> int java.util.Collections.binarySearch(List<? extends Comparable<? super DiversityScoreMapping>> list, DiversityScoreMapping key)

Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.

This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons.

Parameters:
list the list to be searched.
key the key to be searched for.
Returns:
the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
Throws:
ClassCastException - if the list contains elements that are not mutually comparable (for example, strings and integers), or the search key is not mutually comparable with the elements of the list.

http://www.bianceng.cn/Programming/Java/200705/1581.htm

Java 1.2添加了自己的一套实用工具,可用来对数组或列表进行排列和搜索。这些工具都属于两个新类的“静态”方法。这两个类分别是用于排序和搜索数组的Arrays,以及用于排序和搜索列表的Collections。

1. 数组
Arrays类为所有基本数据类型的数组提供了一个过载的sort()和binarySearch(),它们亦可用于String和Object。下面这个例子显示出如何排序和搜索一个字节数组(其他所有基本数据类型都是类似的)以及一个String数组:

//: Array1.java
// Testing the sorting & searching in Arrays
package c08.newcollections;
import java.util.*;

public class Array1 {
  static Random r = new Random();
  static String ssource =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
    "abcdefghijklmnopqrstuvwxyz";
  static char[] src = ssource.toCharArray();
  // Create a random String
  public static String randString(int length) {
    char[] buf = new char[length];
    int rnd;
    for(int i = 0; i < length; i++) {
      rnd = Math.abs(r.nextInt()) % src.length;
      buf[i] = src[rnd];
    }
    return new String(buf);
  }
  // Create a random array of Strings:
  public static
  String[] randStrings(int length, int size) {
    String[] s = new String[size];
    for(int i = 0; i < size; i++)
      s[i] = randString(length);
    return s;
  }
  public static void print(byte[] b) {
    for(int i = 0; i < b.length; i++)
      System.out.print(b[i] + " ");
    System.out.println();
  }
  public static void print(String[] s) {
    for(int i = 0; i < s.length; i++)
      System.out.print(s[i] + " ");
    System.out.println();
  }
  public static void main(String[] args) {
    byte[] b = new byte[15];
    r.nextBytes(b); // Fill with random bytes
    print(b);
    Arrays.sort(b);
    print(b);
    int loc = Arrays.binarySearch(b, b[10]);
    System.out.println("Location of " + b[10] +
      " = " + loc);
    // Test String sort & search:
    String[] s = randStrings(4, 10);
    print(s);
    Arrays.sort(s);
    print(s);
    loc = Arrays.binarySearch(s, s[4]);
    System.out.println("Location of " + s[4] +
      " = " + loc);
  }
} ///:~类的第一部分包含了用于产生随机字串对象的实用工具,可供选择的随机字母保存在一个字符数组中。randString()返回一个任意长度的字串;而readStrings()创建随机字串的一个数组,同时给定每个字串的长度以及希望的数组大小。两个print()方法简化了对示范数组的显示。在main()中,Random.nextBytes()用随机选择的字节填充数组自变量(没有对应的Random方法用于创建其他基本数据类型的数组)。获得一个数组后,便可发现为了执行sort()或者binarySearch(),只需发出一次方法调用即可。与binarySearch()有关的还有一个重要的警告:若在执行一次binarySearch()之前不调用sort(),便会发生不可预测的行为,其中甚至包括无限循环。
对String的排序以及搜索是相似的,但在运行程序的时候,我们会注意到一个有趣的现象:排序遵守的是字典顺序,亦即大写字母在字符集中位于小写字母的前面。因此,所有大写字母都位于列表的最前面,后面再跟上小写字母——Z居然位于a的前面。似乎连电话簿也是这样排序的。

2. 可比较与比较器
但假若我们不满足这一排序方式,又该如何处理呢?例如本书后面的索引,如果必须对以A或a开头的词条分别到两处地方查看,那么肯定会使读者颇不耐烦。
若想对一个Object数组进行排序,那么必须解决一个问题。根据什么来判定两个Object的顺序呢?不幸的是,最初的Java设计者并不认为这是一个重要的问题,否则就已经在根类Object里定义它了。这样造成的一个后果便是:必须从外部进行Object的排序,而且新的集合库提供了实现这一操作的标准方式(最理想的是在Object里定义它)。
针对Object数组(以及String,它当然属于Object的一种),可使用一个sort(),并令其接纳另一个参数:实现了Comparator接口(即“比较器”接口,新集合库的一部分)的一个对象,并用它的单个compare()方法进行比较。这个方法将两个准备比较的对象作为自己的参数使用——若第一个参数小于第二个,返回一个负整数;若相等,返回零;若第一个参数大于第二个,则返回正整数。基于这一规则,上述例子的String部分便可重新写过,令其进行真正按字母顺序的排序:

//: AlphaComp.java
// Using Comparator to perform an alphabetic sort
package c08.newcollections;
import java.util.*;

public class AlphaComp implements Comparator {
  public int compare(Object o1, Object o2) {
    // Assume it's used only for Strings...
    String s1 = ((String)o1).toLowerCase();
    String s2 = ((String)o2).toLowerCase();
    return s1.compareTo(s2);
  }
  public static void main(String[] args) {
    String[] s = Array1.randStrings(4, 10);
    Array1.print(s);
    AlphaComp ac = new AlphaComp();
    Arrays.sort(s, ac);
    Array1.print(s);
    // Must use the Comparator to search, also:
    int loc = Arrays.binarySearch(s, s[3], ac);
    System.out.println("Location of " + s[3] +
     " = " + loc);
  }
} ///:~
通过造型为String,compare()方法会进行“暗示”性的测试,保证自己操作的只能是String对象——运行期系统会捕获任何差错。将两个字串都强迫换成小写形式后,String.compareTo()方法会产生预期的结果。
若用自己的Comparator来进行一次sort(),那么在使用binarySearch()时必须使用那个相同的Comparator。
Arrays类提供了另一个sort()方法,它会采用单个自变量:一个Object数组,但没有Comparator。这个sort()方法也必须用同样的方式来比较两个Object。通过实现Comparable接口,它采用了赋予一个类的“自然比较方法”。这个接口含有单独一个方法——compareTo(),能分别根据它小于、等于或者大于自变量而返回负数、零或者正数,从而实现对象的比较。下面这个例子简单地阐示了这一点:

//: CompClass.java
// A class that implements Comparable
package c08.newcollections;
import java.util.*;

public class CompClass implements Comparable {
  private int i;
  public CompClass(int ii) { i = ii; }
  public int compareTo(Object o) {
    // Implicitly tests for correct type:
    int argi = ((CompClass)o).i;
    if(i == argi) return 0;
    if(i < argi) return -1;
    return 1;
  }
  public static void print(Object[] a) {
    for(int i = 0; i < a.length; i++)
      System.out.print(a[i] + " ");
    System.out.println();
  }
  public String toString() { return i + ""; }
  public static void main(String[] args) {
    CompClass[] a = new CompClass[20];
    for(int i = 0; i < a.length; i++)
      a[i] = new CompClass(
        (int)(Math.random() *100));
    print(a);
    Arrays.sort(a);
    print(a);
    int loc = Arrays.binarySearch(a, a[3]);
    System.out.println("Location of " + a[3] +
     " = " + loc);
  }
} ///:~
当然,我们的compareTo()方法亦可根据实际情况增大复杂程度。

3. 列表
可用与数组相同的形式排序和搜索一个列表(List)。用于排序和搜索列表的静态方法包含在类Collections中,但它们拥有与Arrays中差不多的签名:sort(List)用于对一个实现了Comparable的对象列表进行排序;binarySearch(List,Object)用于查找列表中的某个对象;sort(List,Comparator)利用一个“比较器”对一个列表进行排序;而binarySearch(List,Object,Comparator)则用于查找那个列表中的一个对象(注释⑨)。下面这个例子利用了预先定义好的CompClass和AlphaComp来示范Collections中的各种排序工具:

//: ListSort.java
// Sorting and searching Lists with 'Collections'
package c08.newcollections;
import java.util.*;

public class ListSort {
  public static void main(String[] args) {
    final int SZ = 20;
    // Using "natural comparison method":
    List a = new ArrayList();
    for(int i = 0; i < SZ; i++)
      a.add(new CompClass(
        (int)(Math.random() *100)));
    Collection1.print(a);
    Collections.sort(a);
    Collection1.print(a);
    Object find = a.get(SZ/2);
    int loc = Collections.binarySearch(a, find);
    System.out.println("Location of " + find +
     " = " + loc);
    // Using a Comparator:
    List b = new ArrayList();
    for(int i = 0; i < SZ; i++)
      b.add(Array1.randString(4));
    Collection1.print(b);
    AlphaComp ac = new AlphaComp();
    Collections.sort(b, ac);
    Collection1.print(b);
    find = b.get(SZ/2);
    // Must use the Comparator to search, also:
    loc = Collections.binarySearch(b, find, ac);
    System.out.println("Location of " + find +
     " = " + loc);
  }
} ///:~ ⑨:在本书写作时,已宣布了一个新的Collections.stableSort(),可用它进行合并式排序,但还没有它的测试版问世。

这些方法的用法与在Arrays中的用法是完全一致的,只是用一个列表代替了数组。
TreeMap也必须根据Comparable或者Comparator对自己的对象进行排序。
本文来自-编程入门网:http://www.bianceng.cn/Programming/Java/200705/1581.htm

Collections.binarySearch用法相关推荐

  1. Java当中Collections的用法

    一:上码 package cn.wyj.two;/*** Collections辅助类的使用* * @author 王永杰**/ import java.util.*;public class Dem ...

  2. Java Collections BinarySearch()方法与示例

    集合类binarySearch()方法 (Collections Class binarySearch() method) Syntax: 句法: public static int binarySe ...

  3. java collections 用法_Java Collections unmodifiableCollection()用法及代码示例

    java.util.Collections类的unmodifiableCollection()方法用于返回指定集合的​​不可修改视图.此方法允许模块为用户提供对内部集合的只读访问权限.对返回的集合&q ...

  4. python的userlist_Python Collections.UserList用法及代码示例

    Python列表是array-like数据结构,但与之不同的是它是同质的.单个列表可能包含数据类型,例如整数,字符串以及对象. Python中的列表是有序的,并且有一定数量.根据确定的序列对列表中的元 ...

  5. java 同步 set_Java Collections synchronizedSet()用法及代码示例

    java.util.Collections类的synchronizedSet()方法用于返回由指定集合支持的同步(线程安全)集合.为了保证串行访问,至关重要的是,对后备集的所有访问都必须通过返回的集来 ...

  6. 集合排序 Collections.sort用法

    大半夜,一同学来问这段代码.问了三个问题. 一,这个排序Sort()怎么用?  二,接口作为方法的参数是什么意思? 三,入参直接new Comparator(){}是怎么回事? 先回答第二,三个问题: ...

  7. JAVA的rotate怎么用,Java集合Collections.rotate用法

    函数定义 public static void rotate([List]> list, int distance) 功能描述 按指定距离旋转列表中的元素. PS:个人认为应该叫循环移位比较合适 ...

  8. java addall的用法_Java Collections addAll()用法及代码示例

    java.util.Collections类的addAll()方法用于将所有指定的元素添加到指定的集合中.要添加的元素可以单独指定或作为数组指定.此便捷方法的行为与c.addAll(Arrays.as ...

  9. Python中内建模块collections常见用法总结

    1.Counter Counter是字典对象的一个子类.Counter()函数是collections模块中的函数,它接收一个可迭代对象,例如list.tuple等,返回一个Counter字典.返回C ...

最新文章

  1. mysql++读写BLOB数据
  2. Android源代码获得方法
  3. RocketMQ-初体验RocketMQ(08)-IDEA拉取调测RocketMQ源码
  4. 公司使用360安全产品造成的CRM系统故障!
  5. java理念_java温故而知新(9)OOP(面向对象编程)理念
  6. mysql数据库支持emoji表情的详解
  7. Centos7利用fpm制作rpm包(fpm安装及使用)
  8. SQL的注入式攻击方式和避免方法
  9. IOS开发学习----给表视图设置缩进级别
  10. 省市区三级联动 mysql_javaweb--json--ajax--mysql实现省市区三级联动(附三级联动数据库)...
  11. 高数特殊符号-希腊字母
  12. [Math] 常见的几种最优化方法
  13. Flash游戏开发中的人物走动实现方法
  14. 网线/双绞线相关知识
  15. web服务器主机头文件,在Win2k下建立虚拟Web主机
  16. 2022年9月电子学会Python等级考试试卷(五级)答案解析
  17. 科技爱好者周刊(第 160 期):中年码农的困境
  18. Visual Studio Code 安装Vim插件后,复制(Ctrl C)等快捷键变成Insert 模式的问题
  19. 向大家推荐一下我的笔记APP『百灵』,里面有丰富的面试资料
  20. matlab求信号的瞬时相位,phrase MATLAB中关于信号瞬时相位 频率的提取的代码,值得学习,很实用 267万源代码下载- www.pudn.com...

热门文章

  1. 最短路径(Shortest Paths)
  2. BASIC-11 十六进制转十进制
  3. 人工智能实践之旅 —— 简单说说主要内容和安排
  4. Martix工作室考核题 —— 2019-3-8 第三题
  5. 【Linux网络编程】网络字节序和地址转换
  6. 【Linux】一步一步学Linux——killall命令(125)
  7. 通过命令解锁Oracle,在命令行下进行Oracle用户解锁
  8. oracle10g的silent,Linux 静默(Silent) 安装Oracle 10g
  9. python读取nc文件并转换成csv_Python提取netCDF数据并转换为csv文件
  10. 自己的总结(你必须知道的C 495个问题)