|
| 1 | +package com.viktorvoltz; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +class TwoStrings40 implements Comparable<TwoStrings40> { |
| 6 | + private String first = ""; |
| 7 | + private String second = ""; |
| 8 | + |
| 9 | + public TwoStrings40(String s1, String s2) { |
| 10 | + first = s1; |
| 11 | + second = s2; |
| 12 | + } |
| 13 | + |
| 14 | + // Using only first String to compare: |
| 15 | + public int compareTo(TwoStrings40 ts) { |
| 16 | + return first.compareTo(ts.first); |
| 17 | + } |
| 18 | + |
| 19 | + // Optional inner class to use second String to compare: |
| 20 | + public static class Comp2 implements Comparator<TwoStrings40> { |
| 21 | + public int compare(TwoStrings40 ts1, TwoStrings40 ts2) { |
| 22 | + return ts1.second.compareTo(ts2.second); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + public String toString() { |
| 27 | + return first + " & " + second; |
| 28 | + } |
| 29 | + |
| 30 | + static void printArray(TwoStrings40[] sa) { |
| 31 | + System.out.print("("); |
| 32 | + for (int i = 0; i < sa.length - 1; i++) |
| 33 | + System.out.print(sa[i] + ", "); |
| 34 | + System.out.println(sa[sa.length - 1] + ")"); |
| 35 | + } |
| 36 | + |
| 37 | + public static void main(String[] args) { |
| 38 | + RandomGenerator.String rgs = new RandomGenerator.String(4); |
| 39 | + TwoStrings40[] array = new TwoStrings40[5]; |
| 40 | + List<TwoStrings40> list = new ArrayList<TwoStrings40>(); |
| 41 | + for (int i = 0; i < array.length; i++) { |
| 42 | + String s1 = rgs.next(); |
| 43 | + String s2 = rgs.next(); |
| 44 | + array[i] = new TwoStrings40(s1, s2); |
| 45 | + list.add(new TwoStrings40(s1, s2)); |
| 46 | + } |
| 47 | + System.out.print("Array: "); |
| 48 | + printArray(array); |
| 49 | + System.out.println("List: " + list); |
| 50 | + Arrays.sort(array); |
| 51 | + Collections.sort(list, null); |
| 52 | + System.out.println(); |
| 53 | + System.out.println("Sorted by first word:"); |
| 54 | + System.out.print("Array: "); |
| 55 | + printArray(array); |
| 56 | + System.out.println("List: " + list); |
| 57 | + TwoStrings40.Comp2 comp = new TwoStrings40.Comp2(); |
| 58 | + Arrays.sort(array, comp); |
| 59 | + Collections.sort(list, comp); |
| 60 | + System.out.println(); |
| 61 | + System.out.println("Sorted by second word:"); |
| 62 | + System.out.print("Array: "); |
| 63 | + printArray(array); |
| 64 | + System.out.println("List: " + list); |
| 65 | + } |
| 66 | +} |
0 commit comments