/* A program to illustrate a user-defined interface in a sorting program. Adapted from Barry Holmes, page 308. */ import java.io.*; interface AnyType { public boolean isGreaterThan(AnyType datum); } class IntegerType implements AnyType { private int number; IntegerType() { number = 0; } IntegerType(int i) { number = i; } public boolean isGreaterThan(AnyType datum) { return (this.number > ((IntegerType)datum).number); } public int toInteger() { return number; } } class StringType implements AnyType { private String word; StringType(){word = "";} StringType(String s){word = s;} public boolean isGreaterThan(AnyType datum) { return (this.word.compareTo(((StringType)datum).word) > 0); } public String toString() { return word; } } class Sort { public static void bubbleSort(AnyType[] array) { AnyType temp; int numberOfItems = array.length; boolean cont = true; for (int pass=1; pass != numberOfItems; pass++) { if (cont) { for (int index=0; index != numberOfItems-pass; index++) { cont = false; if (array[index].isGreaterThan(array[index+1])) { temp = array[index]; array[index] = array[index+1]; array[index+1] = temp; cont = true; } // end if } // end for } // end if else break; } // end for } } class InterfaceExample1v2 { public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); IntegerType[] numbers = new IntegerType[5]; for (int i = 0; i < numbers.length; i++) { System.out.print ("Enter data: "); System.out.flush (); numbers[i] = new IntegerType(Integer.parseInt(stdin.readLine())); } System.out.println("Initial list of numbers: "); for (int index=0; index < numbers.length; index++) { System.out.print(numbers[index].toInteger() + "\t"); } System.out.println(); System.out.println("Sorted list of numbers: "); Sort.bubbleSort(numbers); for (int index=0; index < numbers.length; index++) { System.out.print(numbers[index].toInteger() + "\t"); } StringType[] words = new StringType[5]; for (int i = 0; i < words.length; i++) { System.out.print ("Enter data: "); System.out.flush (); words[i] = new StringType(stdin.readLine()); } System.out.println("Initial list of words: "); for (int index=0; index < words.length; index++) { System.out.print(words[index].toString()+"\t"); } System.out.println (); System.out.println("Sorted list of words: "); Sort.bubbleSort(words); for (int index=0; index < words.length; index++) { System.out.print(words[index].toString()+"\t"); } System.out.println(); } }