java基础—— 的两种用法,简单明了 。

时间:2025-02-09 20:13:09
  • /** 
  • * @author guwh 
  • * @version 创建时间:2011-11-3 上午10:49:36 
  • * 类说明 
  • */   
  • package ;  
  •   
  • import ;  
  • import ;  
  • import ;  
  • import ;  
  •   
  • public class SortTest {  
  •       
  •       
  •       
  •     public static void main(String[] args) {  
  •         List<String> lists = new ArrayList<String>();  
  •         List<A> list = new ArrayList<A>();  
  •         List<B> listB = new ArrayList<B>();  
  •         ("5");  
  •         ("2");  
  •         ("9");  
  •         //lists中的对象String 本身含有compareTo方法,所以可以直接调用sort方法,按自然顺序排序,即升序排序  
  •         (lists);  
  •           
  •         A aa = new A();  
  •         ("aa");  
  •         (1);  
  •         A bb = new A();  
  •         ("bb");  
  •         (2);  
  •         (bb);  
  •         (aa);  
  •         //list中的对象A实现Comparable接口  
  •         (list);  
  •           
  •         B ab = new B();  
  •         ("ab");  
  •         ("1");  
  •         B ba = new B();  
  •         ("ba");  
  •         ("2");  
  •         (ba);  
  •         (ab);  
  •         //根据重载方法来实现  
  •         (listB,new Comparator<B>(){  
  •             @Override  
  •             public int compare(B b1, B b2) {  
  •                 return ().compareTo(());  
  •             }  
  •               
  •         });  
  •           
  •         (lists);  
  •         (list);  
  •         (listB);  
  •           
  •     }  
  •   
  • }  
  •   
  • class A implements Comparable<A>{  
  •     private String name;  
  •     private Integer order;  
  •     public String getName() {  
  •         return name;  
  •     }  
  •     public void setName(String name) {  
  •         this.name = name;  
  •     }  
  •       
  •     public Integer getOrder() {  
  •         return order;  
  •     }  
  •     public void setOrder(Integer order) {  
  •         this.order = order;  
  •     }  
  •     @Override  
  •     public String toString() {  
  •         return "name is "+name+" order is "+order;  
  •     }  
  •     @Override  
  •     public int compareTo(A a) {  
  •         return this.(());  
  •     }  
  •       
  • }  
  •   
  • class B{  
  •     private String name;  
  •     private String order;  
  •     public String getName() {  
  •         return name;  
  •     }  
  •     public void setName(String name) {  
  •         this.name = name;  
  •     }  
  •     public String getOrder() {  
  •         return order;  
  •     }  
  •     public void setOrder(String order) {  
  •         this.order = order;  
  •     }  
  •     @Override  
  •     public String toString() {  
  •         return "name is "+name+" order is "+order;  
  •     }  
  • }  
  •   
  • 打印的结果为:  
  •  [259]  
  • [name is aa order is 1, name is bb order is 2]  
  • [name is ab order is 1, name is ba order is 2]