栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Comparable接口实现对象数组排序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Comparable接口实现对象数组排序

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());
        
    }
    
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/345964.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号