Comparable接口详解

来源:互联网 发布:阿里云maven镜像站 编辑:程序博客网 时间:2024/05/18 03:24

对象比较大小,只能通过继承Comparable这个接口并实现接口的compareTo方法,这个方法返回的是int值。在比较对象大小的时候,是根据compareTo的返回值来确定的,如果返回值为负代表小于,正数代表大于,零代表相等。

.通过 Collections.sort()Arrays.sort()进行自动排序。

例子如下:

import java.util.*;public class Test{public static void main(String[] args){H h1=new H(1); H h2=new H(2); H h3=new H(3); H h4=new H(4); H h5=new H(5); H[] h={h1,h2,h3,h5,h4};for(H x:h){System.out.println(x.i);}Arrays.sort(h);for(H x:h){System.out.println(x.i);}}}class H implements Comparable<H> {int i;public H(int j){this.i=j;}public int compareTo(H h){if(this.i<h.i){return -1;}if(this.i>h.i){return 1;}return 0;}}


0 1