OnJava8-Examples/arrays/ComparatorTest.java

39 lines
1.2 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// arrays/ComparatorTest.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Implementing a Comparator for a class
2015-06-15 17:47:35 -07:00
import java.util.*;
import onjava.*;
2016-01-25 18:05:55 -08:00
import static onjava.ArrayShow.*;
2015-06-15 17:47:35 -07:00
class CompTypeComparator implements Comparator<CompType> {
public int compare(CompType o1, CompType o2) {
return (o1.j < o2.j ? -1 : (o1.j == o2.j ? 0 : 1));
}
}
public class ComparatorTest {
public static void main(String[] args) {
2016-01-25 18:05:55 -08:00
CompType[] a = new CompType[12];
Arrays.setAll(a, n -> CompType.get());
show("Before sorting", a);
2015-06-15 17:47:35 -07:00
Arrays.sort(a, new CompTypeComparator());
2016-01-25 18:05:55 -08:00
show("After sorting", a);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2016-07-22 14:45:35 -06:00
Before sorting: [[i = 35, j = 37], [i = 41, j = 20], [i =
77, j = 79]
, [i = 56, j = 68], [i = 48, j = 93], [i = 70, j = 7]
, [i = 0, j = 25], [i = 62, j = 34], [i = 50, j = 82]
, [i = 31, j = 67], [i = 66, j = 54], [i = 21, j = 6]
2015-06-15 17:47:35 -07:00
]
2016-07-22 14:45:35 -06:00
After sorting: [[i = 21, j = 6], [i = 70, j = 7], [i = 41,
j = 20]
, [i = 0, j = 25], [i = 62, j = 34], [i = 35, j = 37]
, [i = 66, j = 54], [i = 31, j = 67], [i = 56, j = 68]
, [i = 77, j = 79], [i = 50, j = 82], [i = 48, j = 93]
2015-06-15 17:47:35 -07:00
]
2015-09-07 11:44:36 -06:00
*/