//: net/mindview/util/Generated.java
package net.mindview.util;
import java.util.*;
public class Generated
{
// Fill an existing array:
public static <T> T[] array(T[] a, Generator<T> gen)
{
return new CollectionData<T>(gen, a.length).toArray(a);
}
// Create a new array:
@SuppressWarnings("unchecked")
public static <T> T[] array(Class<T> type,
Generator<T> gen, int size)
{
T[] a =
(T[])java.lang.reflect.Array.newInstance(type, size);
return new CollectionData<T>(gen, size).toArray(a);
}
} ///:~
package Lesson16Arrays;
//: arrays/CompType.java
// Implementing Comparable in a class.
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
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;
}
public String toString()
{
String result = "[i = " + i + ", j = " + j + "]";
if(count++ % 3 == 0) //当个数恰好是3的倍数时候换行,并++,每输出一次就++
result += "\n";
return result;
}
public int compareTo(CompType rv) //sort函数会调用这个
{
return (i < rv.i ? -1 : (i == rv.i ? 0 : 1));//要比较的对象的i比这个大的话,就返回-1
}
private static Random r = new Random(47); //私有静态的,产生
public static Generator<CompType> generator()
{
return new Generator<CompType>()
{
public CompType next()
{
return new CompType(r.nextInt(100),r.nextInt(100)); //在 0(包括)和指定值(不包括)之间均匀分布的 int 值
}
};
}
public static void main(String[] args)
{
CompType[] a =
Generated.array(new CompType[12], generator()); //后面那个参数每次调用的时候随机产生数据,用来初始化前面那个对象
print("before sorting:");
print(Arrays.toString(a));
Arrays.sort(a);
print("after sorting:");
print(Arrays.toString(a));
}
}
输出:
before sorting: obj1
[[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]
] obj1
after sorting: obj1
[[i = 98, j = 61], [i = 93, j = 61], [i = 88, j = 28]
, [i = 68, j = 0], [i = 61, j = 29], [i = 58, j = 55]
, [i = 51, j = 89], [i = 22, j = 7], [i = 20, j = 58]
, [i = 16, j = 40], [i = 11, j = 22], [i = 9, j = 78]
] obj1