2015-09-07 11:44:36 -06:00
|
|
|
|
// arrays/CompType.java
|
2015-11-14 16:18:05 -08:00
|
|
|
|
// <20>2016 MindView LLC: see Copyright.txt
|
2015-06-15 17:47:35 -07:00
|
|
|
|
// Implementing Comparable in a class.
|
|
|
|
|
import java.util.*;
|
2015-11-03 12:00:44 -08:00
|
|
|
|
import java.util.function.*;
|
2015-11-11 20:20:04 -08:00
|
|
|
|
import onjava.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
|
|
public class CompType implements Comparable<CompType> {
|
|
|
|
|
int i;
|
|
|
|
|
int j;
|
|
|
|
|
private static int count = 1;
|
|
|
|
|
public CompType(int n1, int n2) {
|
|
|
|
|
i = n1;
|
|
|
|
|
j = n2;
|
|
|
|
|
}
|
|
|
|
|
@Override
|
|
|
|
|
public String toString() {
|
|
|
|
|
String result = "[i = " + i + ", j = " + j + "]";
|
|
|
|
|
if(count++ % 3 == 0)
|
|
|
|
|
result += "\n";
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
@Override
|
|
|
|
|
public int compareTo(CompType rv) {
|
|
|
|
|
return (i < rv.i ? -1 : (i == rv.i ? 0 : 1));
|
|
|
|
|
}
|
|
|
|
|
private static Random r = new Random(47);
|
2015-11-03 12:00:44 -08:00
|
|
|
|
public static Supplier<CompType> generator() {
|
2015-06-15 17:47:35 -07:00
|
|
|
|
return () ->
|
2015-09-07 11:44:36 -06:00
|
|
|
|
new CompType(r.nextInt(100), r.nextInt(100));
|
2015-06-15 17:47:35 -07:00
|
|
|
|
}
|
|
|
|
|
public static void main(String[] args) {
|
|
|
|
|
CompType[] a =
|
|
|
|
|
Generated.array(new CompType[12], generator());
|
2015-11-03 12:00:44 -08:00
|
|
|
|
System.out.println("before sorting:");
|
|
|
|
|
System.out.println(Arrays.toString(a));
|
2015-06-15 17:47:35 -07:00
|
|
|
|
Arrays.sort(a);
|
2015-11-03 12:00:44 -08:00
|
|
|
|
System.out.println("after sorting:");
|
|
|
|
|
System.out.println(Arrays.toString(a));
|
2015-06-15 17:47:35 -07:00
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
|
}
|
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
|
before sorting:
|
|
|
|
|
[[i = 58, j = 55], [i = 93, j = 61], [i = 61, j = 29]
|
|
|
|
|
, [i = 68, j = 0], [i = 22, j = 7], [i = 88, j = 28]
|
|
|
|
|
, [i = 51, j = 89], [i = 9, j = 78], [i = 98, j = 61]
|
|
|
|
|
, [i = 20, j = 58], [i = 16, j = 40], [i = 11, j = 22]
|
|
|
|
|
]
|
|
|
|
|
after sorting:
|
|
|
|
|
[[i = 9, j = 78], [i = 11, j = 22], [i = 16, j = 40]
|
|
|
|
|
, [i = 20, j = 58], [i = 22, j = 7], [i = 51, j = 89]
|
|
|
|
|
, [i = 58, j = 55], [i = 61, j = 29], [i = 68, j = 0]
|
|
|
|
|
, [i = 88, j = 28], [i = 93, j = 61], [i = 98, j = 61]
|
|
|
|
|
]
|
2015-09-07 11:44:36 -06:00
|
|
|
|
*/
|