// A program to illustrate JAVA interfaces. import java.util.Scanner; interface AnyType { public boolean isBetterThan(AnyType datum); } class IntegerType implements AnyType { private int number; public IntegerType() { number = 0; } public IntegerType(int i) { number = i; } public boolean isBetterThan(AnyType datum) { return (this.number > ((IntegerType)datum).number); } public int toInteger() { return number; } } class StringType implements AnyType { private String word; public StringType(){ word = ""; } public StringType(String s){ word = s; } public boolean isBetterThan(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; for (int pass=1; pass != numberOfItems; pass++) { for (int index=0; index != numberOfItems-pass; index++) { if (array[index].isBetterThan(array[index+1])) { temp = array[index]; array[index] = array[index+1]; array[index+1] = temp; } } } } } class SortingExample { public static void main(String[] args) { Scanner scan = new Scanner(System.in); IntegerType[] numbers = new IntegerType[5]; System.out.println (); System.out.println ("Sorting integers"); System.out.println (); for (int i = 0; i < numbers.length; i++) { System.out.print ("Enter an integer: "); System.out.flush (); numbers[i] = new IntegerType(scan.nextInt()); } System.out.println (); 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"); } scan.nextLine(); StringType[] words = new StringType[5]; System.out.println (); System.out.println (); System.out.println ("Sorting strings"); System.out.println (); for (int i = 0; i < words.length; i++) { System.out.print ("Enter a string: "); System.out.flush (); words[i] = new StringType(scan.nextLine()); } System.out.println (); 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 (); } }