Java 集合排序方法 集合…

  1. package  v08;
  2.  
  3. import  java.util.*;
  4. public   class  TestSort {
  5.  
  6.   public   static   void  main(String[]  args {
  7.    //  TODO  Auto-generated method stub
  8.    List   l1   new   LinkedList ();
  9.    l1 .add( new  Name( "Karl" , "M" )) ;
  10.    l1 .add( new  Name( "Steven" , "Lee" )) ;
  11.    l1 .add( new  Name( "John" , "O" )) ;
  12.    l1 .add( new  Name( "Tom" , "M" )) ;
  13.   System. out .println( l1 ); [ Karl  M,  Steven  Lee, John O, Tom M]
  14.    Collections. sort ( l1 ) ;
  15.   System. out .println( l1 ); //[John O,  Karl  M,  Steven  Lee, Tom M]
  16.    List   l2   new   LinkedList ();
  17.    l2 .add( "String" ) ;
  18.    l2 .add( new  Integer(100)) ;
  19.   System. out .println( l2 ); //集合的toString方法就是每个元素(对象)的toString方法联合[String, 100]
  20.  
  21.   
  22.  
  23.  }
  24.  
  25. }
  26.  
  27. class  Name  implements   Comparable {
  28.  
  29.   private  String  firstName , lastName ;
  30.  
  31.   public   int  compareTo(Object  obj ){
  32.   Name  name  (Name)  obj ;
  33.          int   a   lastName .compareTo( lastName );
  34.          return   a  !=  a  :
  35.            firstName .compareTo( name . firstName );
  36.  }
  37.  
  38.   public  Name(String  firstName ,String  lastName ){
  39.    this . firstName   firstName ;
  40.    this . lastName   lastName ;
  41.  }
  42.  
  43.   public  String getFirstName(){
  44.    return   firstName ;
  45.  }
  46.   public  String getLastName(){
  47.    return   lastName ;
  48.  }
  49.   public  String toString(){
  50.    return   firstName  + "   lastName ;
  51.  }
  52.  
  53.   public   boolean  equals(Object  obj ){
  54.    if  ( obj   instanceof  Name){
  55.    Name  name  (Name)  obj ;
  56.     return   firstName .equals( name . firstName &&
  57.       lastName .equals( name . lastName );
  58.   }
  59.    return   super .equals( obj );
  60.  }
  61.   public   int  hashCode(){
  62.    return   firstName .hashCode();
  63.  }
  64. }
  65.  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值