Java书p167习题8

习题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);
		}
	}
}

输出:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值