SortArray3.java
Select all
/* SortArray3.java David G. Klick 2/1/06 CIS 260 This program demonstrates the use of a custom Comparator for changing the sort order. In this case, the Comparator simply changes the order to descending. It also uses a new feature of Java 1.5 called Generics, which are similar to templates in C++. */ import java.util.*; public class SortArray3 { public static void main(String[] args) { Comparator
desc = new DescendingComparator(); Comparator
odds = new OddsFirstComparator(); Integer[] n = { new Integer(8), new Integer(-8), new Integer(13), new Integer(7), new Integer(42), new Integer(5) }; Arrays.sort(n, desc); System.out.print("Descending: "); for (int i : n) System.out.print(i + " "); Arrays.sort(n, odds); System.out.print("\n\nOdds first: "); for (int i : n) System.out.print(i + " "); } } /* This Comparator orders all Integers in descending numerical order. */ class DescendingComparator implements Comparator
{ public int compare(Integer a, Integer b) { return b - a; } } /* This Comparator makes all odd numbers come before all even numbers. Within that order, the numbers are sorted by numerical value. */ class OddsFirstComparator implements Comparator
{ public int compare(Integer a, Integer b) { boolean a_odd = a % 2 != 0; boolean b_odd = b % 2 != 0; if (a_odd && !b_odd) return -1; else if (!a_odd && b_odd) return 1; else return a - b; } } /* Sample run: Descending: 42 13 8 7 5 -8 Odds first: 5 7 13 -8 8 42 */