CPS 100, Spring 2005, Recitation 2 During

In this recitation you'll study and reason about the java.lang.Comparable and java.util.Comparator interfaces. You'll also see a useful method of the String class: split, which splits a string into parts based on a delimeter. We'll use whitespace as the delimiter, but you can use other characters (or more generally, regular expressions.)

Code for the recitation is in ComparableStuff.java. The output generated from executing the main method is shown below.

	original

ape ant anteater cat dingo monkey mongoose lion leopard goat giraffe snake yak 
ant anteater ape cat dingo giraffe goat leopard lion mongoose monkey snake yak 

	reversed follows

ape ant anteater cat dingo monkey mongoose lion leopard goat giraffe snake yak 
yak snake monkey mongoose lion leopard goat giraffe dingo cat ape anteater ant

	length sorted

ant ape cat yak goat lion dingo snake monkey giraffe leopard anteater mongoose 

	show split

banana watermelon apple lemon mango orange 
apple banana lemon mango orange watermelon 

  1. Explain the two lines of output under the label original, why does anteater come before ant in the second line, but after it in the first line?
    
    
    
    
    
  2. Explain why yak comes first in the second line under the label reversed follows and why ant is last in that line.
    
    
    
    
    
  3. If the toString method in inner class RevString is changed as follows: public String toString(){ return ""+myString.length(); } the only part of the output changed when the program is run is shown below. Explain both lines of this new output.
    	reversed follows
    
    3 8 3 5 6 8 4 7 4 7 5 3 
    3 5 6 8 4 7 4 7 5 3 3 8 
    
    
  4. The three lines of code from main here: System.out.println("\n\tlength sorted\n"); Arrays.sort(list, new LengthComparator()); comp.printArray(list); are responsible for generating this output:
    	length sorted
    
    ant ape cat yak goat lion dingo snake monkey giraffe leopard anteater mongoose 
    
    
    Explain this output: why does yak come before goat, why does anteater come after ape, and where would zebra appear in the output if it was in the array list?
    
    
    
    
    
    
  5. If the three lines above are changed to the following (one statement added) what one new line of output is generated, why? System.out.println("\n\tlength sorted\n"); comp.printArray(list); Arrays.sort(list, new LengthComparator()); comp.printArray(list);

  6. Based on the output shown, describe what the String method split does in your own words. Note that the String literal "\\s+" is a regular-expression meaning 'any whitespace'.
    
    
    
  7. To Hand In
    Design and implement a new Comparator class named AlphaLength so that if used in place of LengthComparator would have the following characteristics:


Comments?
Last modified: Thu Jan 27 11:35:18 EST 2005