java 类比较大小(实现Comparable接口)

2019-04-14 17:15发布

import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 两个类要想比较大小, * 就必须实现Comparable接口,类型参数T通常设为实现该接口的类名 * 实现Comparable接口后,还要覆盖public int compareTo( object)方法 * 如果两个对象相等返回0 * 当前对象大于方法传过来的对象时,返回一个正整数 * 当前对象小于方法传过来的对象时,返回一个负整数 * 而且相等时必须和equals()方法保持一致,即eaquls()方法要返回true * 否则相反 */ public class comparablePoint implements Comparable{ public int x; public int y; public comparablePoint(int x,int y) { this.x=x; this.y=y; } public int compareTo(comparablePoint point) { int s1=x*x+y*y; int s2=point.x-point.x+point.y*point.y; return s1-s2; } public String toString() { return "["+x+","+y+"]"; } public static void main(String args[]) { if(new comparablePoint(3, 4).compareTo(new comparablePoint(1, 1))>0) System.out.println("true"); //线性表 List points=new ArrayList(); points.add(new comparablePoint(1, 6)); points.add(new comparablePoint(3, 4)); points.add(new comparablePoint(5, 2)); System.out.println(points); Collections.sort(points);//调用Collections工具类进行排序 System.out.println("排序后的情况"); System.out.println(points); } } 结果 true [[1,6], [3,4], [5,2]] 排序后的情况 [[3,4], [5,2], [1,6]]