集册 Java实例教程 集合方法binarySearch。

集合方法binarySearch。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

497
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
集合方法binarySearch。


import java.util.List;

import java.util.Arrays;// from 时 代 J a v a 公 众 号 - N o w J a v  a . c o m

import java.util.Collections;

import java.util.ArrayList;


public class Main 

{

   public static void main(String[] args)

   {

      // create an ArrayList<String> from the contents of colors array

      String[] colors = {"red", "white", "blue", "black", "yellow", 

         "purple", "tan", "pink"};

      List<String> list = /**来自 N o w J a v a . c o m - 时代Java**/

         new ArrayList<>(Arrays.asList(colors));


      Collections.sort(list); // sort the ArrayList

      System.out.printf("Sorted ArrayList: %s%n", list);


      // search list for various values

      printSearchResults(list, "black"); // first item

      printSearchResults(list, "red"); // middle item

      printSearchResults(list, "pink"); // last item

      printSearchResults(list, "aqua"); // below lowest

      printSearchResults(list, "gray"); // does not exist

      printSearchResults(list, "teal"); // does not exist

   }      


   // perform search and display result

   private static void printSearchResults(

      List<String> list, String key)

   {

      int result = 0;


      
展开阅读全文