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());
}
}