java.lang下面有一个接口:Comparable(可比较的)

对于自定义对象,Sort不知道规则,所以无法比较。这种情况下一定要定义排序规则。方式有两种:

java.lang下面有一个接口:Comparable(可比较的)

可以让自定义对象实现一个接口,这个接口只有一个方法comparableTo(Object o)

其规则是当前对象与o对象进行比较,其返回一个int值,系统根据此值来进行排序。

如 当前对象>o对象,则返回值>0;(可将返回值定义为1)

如 当前对象=o对象,则返回值=0;

如 当前对象<o对象,则返回值〈0。(可将返回值定义为-1)

看TestArraylist的java代码。

我们通过返回值1和-1位置的调换来实现升序和降序排列的转换。

 1 package TomTexts;
 2 
 3  
 4     abstract class fatherClass
 5     {
 6         abstract void abstractMethod();
 7         void printMethod()
 8         {
 9             System.out.println("fatherClass function! ");    
10         }
11     }
12     class childClass extends fatherClass
13     {
14         void abstractMethod()
15         {
16             System.out.println("childClass function! ");
17         }
18     }
19     public class TomTexts_07
20     {
21     public static void main(String args[])
22     {
23         childClass c=new childClass();
24         c.abstractMethod();
25         c.printMethod();
26 
27     }   
28 }
原文地址:https://www.cnblogs.com/borter/p/9420325.html