Comparable接口实现对象数组排序

本文介绍了如何在Java中使用Comparable接口为复数类定义排序,通过compareTo方法计算模长并按降序排列。示例展示了如何创建复数对象数组,调用Arrays.sort进行排序,并输出排序后的复数信息。
摘要由CSDN通过智能技术生成

1.一个类实现Comparable接口

public class 类名 implements Comparable{

    ...
}

 

2.实现Comparable接口,重写compareTo方法

public class 类名 implements Comparable{

    ...
    public compareto(Object other){
        类名 otherone = (类名)other;
        return Flout.compare(this.方法名,otherone.方法名);    //包装类看具体代码中数据类型
    }
}

 

3.主方法中调用排序

public class 类名 {

    public static void main(String[] args){
        ...
        Arrays.sort(对象数组名);
    }
}

 

示例:

/*编写复数类,为该类定义信息输出方法,计算模长的方法。*/
public class ComplexNumber implements Comparable {

    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;
    }
    
    public int compareTo(Object otherone) {        //实现Comparable接口
        ComplexNumber other = (ComplexNumber)otherone;
        return Double.compare(length(),other.length());
    }

}

 

/*编写测试类,建立复数的动态数组,对输入的复数按照模的大小进行排序,并按照从大到小的顺序输出各个复数的值。
*/
import java.util.Arrays;
import java.util.Scanner;        //导入两个包

public class Test {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        ComplexNumber[] num = new ComplexNumber[3];
        System.out.println("请输入三个复数:");
        num[0] = new ComplexNumber(in.nextDouble(), in.nextDouble());
        num[1] = new ComplexNumber(in.nextDouble(), in.nextDouble());
        num[2] = new ComplexNumber(in.nextDouble(), in.nextDouble());
        //对象数组排序
        System.out.println("after sort:");
        Arrays.sort(num);
        //输出按模长排序后的对象数组
        for(ComplexNumber s : num)
            System.out.println(s.getinfo());
        
    }
    
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

陪你看日出.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值