Advertisement
math230

Demo Arrays.sort and Comparable Interface

Sep 30th, 2018
557
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 KB | None | 0 0
  1. //****************************************************
  2. // This program demonstrates the Arrays.sort method. *
  3. //****************************************************
  4.  
  5. import java.util.Arrays;  //for Arrays.sort()
  6. import java.io.File;
  7. import java.util.ArrayList;
  8.  
  9. //This example demonstrates that the static Arrays.sort() method
  10. // works with objects that implement the Comparable interface
  11.  
  12.  
  13. public class SortDemo
  14. {
  15.      public static void main(String [] args)
  16.      { 
  17.         String[] lakers = new String[4];
  18.         lakers[0] = "kobe";
  19.         lakers[1] = "zo";
  20.         lakers[2] = "ginobli";
  21.         lakers[3] = "gasol";
  22.  
  23.         // Arrays.sort()can work on objects that implement
  24.         // the Comparable interface
  25.         for(String s: lakers )
  26.             System.out.print( s + " " );
  27.         System.out.println();
  28.        
  29.         Arrays.sort( lakers );
  30.        
  31.         for(String s: lakers )
  32.             System.out.print( s + " " );
  33.         System.out.println();
  34.        
  35.        
  36.         Integer[] numbers = { 9, 2, 7, 12, 1 };  //auto box
  37.         // Display the array elements unsorted.
  38.         for(Integer i: numbers )
  39.             System.out.print( i + " " );
  40.         System.out.println();
  41.  
  42.         // Sort the array.
  43.         Arrays.sort(numbers);
  44.        
  45.         // Display the array elements sorted.
  46.         for(Integer i: numbers )
  47.             System.out.print( i + " " );
  48.         System.out.println();  
  49.        
  50.        
  51.         /*
  52.         //run-time error since objects aren't mutually comparable
  53.         Object[] foo = new Object[2];
  54.         foo[0] = new String("joe");
  55.         foo[1] = new Integer( 365 );
  56.         //Arrays.sort(foo);  //run-time error since objects aren't mutually comparable
  57.         for(int i =0; i< foo.length; i++)
  58.             System.out.println(foo[i]);
  59.        
  60.         */
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement