Searching array with Comparator : Arrays « Utility Classes « SCJP






import java.util.Arrays;
import java.util.Comparator;

public class MainClass{
  public static void main(String[] args) {
    String[] sa = { "one", "two", "three", "four" };

    Arrays.sort(sa); 
    for (String s : sa){
      System.out.print(s + " ");
    }  
    System.out.println("\none = " + Arrays.binarySearch(sa, "one")); 

    System.out.println("now reverse sort");
    ReSortComparator rs = new ReSortComparator(); 
    Arrays.sort(sa, rs);
    for (String s : sa){
      System.out.print(s + " ");
    }  
    System.out.println("\none = " + Arrays.binarySearch(sa, "one")); 
    System.out.println("one = " + Arrays.binarySearch(sa, "one", rs));
  }
}

class ReSortComparator implements Comparator<String> { 
  public int compare(String a, String b) {
    return b.compareTo(a);
  }
}
four one three two 
one = 1
now reverse sort
two three one four 
one = -1
one = 2








8.21.Arrays
8.21.1.java.util.Arrays class contains static methods for sorting and searching arrays.
8.21.2.Collections provide a number of static methods for searching, sorting, and converting Collection objects.
8.21.3.Converting Arrays to Lists to Arrays
8.21.4.Searching array with Comparator