2015-09-07 11:44:36 -06:00
|
|
|
// arrays/CompType.java
|
2020-10-07 13:35:40 -06:00
|
|
|
// (c)2020 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.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Implementing Comparable in a class
|
2015-06-15 17:47:35 -07:00
|
|
|
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.*;
|
2016-01-25 18:05:55 -08:00
|
|
|
import static onjava.ArrayShow.*;
|
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));
|
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
private static SplittableRandom r =
|
|
|
|
new SplittableRandom(47);
|
|
|
|
public static CompType get() {
|
|
|
|
return new CompType(r.nextInt(100), r.nextInt(100));
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
2016-01-25 18:05:55 -08:00
|
|
|
CompType[] a = new CompType[12];
|
|
|
|
Arrays.setAll(a, n -> get());
|
|
|
|
show("Before sorting", a);
|
2015-06-15 17:47:35 -07:00
|
|
|
Arrays.sort(a);
|
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:
|
2017-05-10 11:45:39 -06:00
|
|
|
Before sorting: [[i = 35, j = 37], [i = 41, j = 20], [i
|
|
|
|
= 77, j = 79]
|
2016-07-22 14:45:35 -06:00
|
|
|
, [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
|
|
|
]
|
2017-05-10 11:45:39 -06:00
|
|
|
After sorting: [[i = 0, j = 25], [i = 21, j = 6], [i =
|
|
|
|
31, j = 67]
|
2016-07-22 14:45:35 -06:00
|
|
|
, [i = 35, j = 37], [i = 41, j = 20], [i = 48, j = 93]
|
|
|
|
, [i = 50, j = 82], [i = 56, j = 68], [i = 62, j = 34]
|
|
|
|
, [i = 66, j = 54], [i = 70, j = 7], [i = 77, j = 79]
|
2015-06-15 17:47:35 -07:00
|
|
|
]
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|