Java對數組對象進行排序


下面是一組對數組對象進行排序的代碼:

package com.sun;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test09 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        Dog dog[] = new Dog[3];
         dog[0]= new Dog("wangchai",10);
         dog[1]= new Dog("laifu",9);
         dog[2]= new Dog("ww",20);
        Arrays.sort(dog);

        for(int i=0;i<dog.length;i++){
            System.out.println(dog[i].name);
        }
    }

}

class Dog implements  Comparable{
    public Integer tizhong = 0;
    public String name = "";
    public Dog(String name, int tizhong) {
        this.name = name;
        this.tizhong = tizhong;
    }
    //按年齡排序
    @Override
/*    public int compareTo(Object o) {
        // TODO Auto-generated method stub
        Dog s=(Dog)o;
        return tizhong>s.tizhong?1:(tizhong==s.tizhong?0:-1);
    }*/
    //按名字排序
/*    public int compareTo(Object o)
       {
        Dog s=(Dog)o;
             int result=name.compareTo(s.name);
             return result;
       }*/
    //如果先按數字再按字符排序,則這樣寫:
     public int compareTo(Object o)
      {
        Dog s=(Dog)o;
             int result= tizhong>s.tizhong?1:(tizhong==s.tizhong?0:-1);
              if (0==result){
                  result=name.compareTo(s.name);
               }
             return result;
      }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM