习题8
如何实现集合对象排序?定义一个复数类并按照复数的实部大小对复数对象进行排序。
代码
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class Complex {
int real; // 实部
int imaginary; // 虚部
public void print(Complex com) {
System.out.print(((Integer)com.real).toString()+"+"+((Integer)com.imaginary).toString()+"i ");
}
public Complex(int real, int imaginary) { // 构造方法
this.real = real;
this.imaginary = imaginary;
print(this); // 调用自身print方法
}
public static void main(String[] args) {
List<Complex> list = new ArrayList<Complex>(); // 建立一个泛型数组专门来存储Complex类
System.out.println("原始:");
for(int i=0;i<10;++i) { // 随机生成10个复数
int real = (int)(Math.random()*10); // 随机生成1~10的整数
int imaginary = (int)(Math.random()*10);
list.add(new Complex(real, imaginary)); // 用real和imaginary构造一个Complex并且加入list中
}
System.out.println();
System.out.println("排序后:");
// 自定义集合元素比较器(匿名内部类)
Collections.sort(list, new Comparator<Complex>() {
public int compare(Complex o1, Complex o2) {
return o1.real - o2.real;
}
});
// Iterator遍历
for(Iterator<Complex> it = list.iterator(); it.hasNext(); ) {
Complex object = (Complex)it.next();
object.print(object);
}
}
}
输出: