动态数组ArrayList类(列表)实现按对象属性排序

 1.首先创建一个复数类,具有实部和虚部两个成员变量,获得信息的方法,以及复数的模长。

public class ComplexNumber {

	double real;
	double image;
	
	public ComplexNumber() {	}
	public ComplexNumber(double real,double image) {
		// TODO Auto-generated constructor stub
	
		this.real = real;
		this.image = image;
	}
	
	String getinfo() {
		
		String s;
		s = real + "+" + image + "i";
		return s;
	}
	
	public double length() {
		
		return this.real*this.real + this.image*this.image;
	}
	
	

}

2.在测试类中创建动态对象数组,并实现按对象属性(模长)排序。

public class Test {

	public static void main(String[] args) {

		int n;
		Scanner in = new Scanner(System.in);
		ArrayList<ComplexNumber> myList = new ArrayList<>();
		System.out.println("test2-请输入要输入的复数个数:");
		n = in.nextInt();
		System.out.println("请输入复数:");
		System.out.println("(格式为实部 虚部)");
		for(int i = 0; i < n; i++) {
			myList.add(new ComplexNumber(in.nextDouble(), in.nextDouble()));
		}

		Collections.sort(myList,new Comparator<ComplexNumber>() {

			@Override
			public int compare(ComplexNumber one, ComplexNumber other) {
				
				return Double.compare(one.length(), other.length());
			}
			
		});
		
		System.out.println("after sort:");
		for(int i = 0; i < myList.size(); i++)
			System.out.println(myList.get(i).getinfo());
		
		
	}
	
}

Collections.sort(列表名,匿名对象Comparator);

new Comparator<要实现排序的类>() {

			@Override
			public int compare(类名 one, 类名 other) {
				
				return Double.compare(one.属性, other.属性);
			}
			
		}

当然,也可采用存入数据库的方式,在数据库里实现排序,这里不做详细介绍。 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陪你看日出.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值