泛型的排序問題(Collections.sort及Comparable的應用)

一.前言java

   java中對泛型(集合類型)排序的問題,主要採用了兩張方式一種是對要排序的實體類,實現Comparable接口,另外一種方式,Collections集合工具類進行排序。ide

二.實現Comparable接口方式工具

package com.shine.demo.test;

import java.io.Serializable;

public class Car implements Serializable, Comparable<Car> {
    
    /**
     * 序列化版本.
     */
    private static final long serialVersionUID = 5854674665110917200L;

    private Long id;
    
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Car car) {
        if(!this.id.equals(car.getId()))
            return this.id.compareTo(car.getId());
        else if(!this.name.equals(car.getName()))
            return this.name.compareTo(car.getName());
        
        return 0;
    }
    
    @Override
    public String toString() {
        return "Car的id爲:" + this.id + ",名稱爲:" + this.name;
    }
    
}

實現了Comparable接口,重寫compareTo方法。this


三.Collections集合工具spa

package com.shine.demo.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Test {
    
    public static void main(String[] args) {
        
        Car car = new Car();
        car.setId(1L);
        car.setName("小汽車");
        
        Car car1 = new Car();
        car1.setId(2L);
        car1.setName("貨車");
        
        Car car2 = new Car();
        car2.setId(3L);
        car2.setName("載客小汽車");
        
        Car car3 = new Car();
        car3.setId(4L);
        car3.setName("出租車");
        
        //使用Comparable與Set進行排序
        Set<Car> cars = new TreeSet<Car>();
        cars.add(car);
        cars.add(car3);
        cars.add(car1);
        cars.add(car2);    
        
        for (Car carInfo : cars) {
            System.out.println(carInfo);
        }
        
        //經常使用Collections的sort排序
        List<Car> carList = new ArrayList<Car>();
        carList.add(car);
        carList.add(car3);
        carList.add(car1);
        carList.add(car2);    
        
        Collections.sort(carList, new Comparator<Car>() {
            
            @Override
            public int compare(Car car1, Car car2) {
                return (int) (car1.getId() - car2.getId());
            }
        });
        
        for (Car carInfoList : carList) {
            System.out.println(carInfoList);
        }
        
        
    }

}

採用了Collections的sort排序方法,其原理是利用了Comparator的類,進行排序。
結果:code

相關文章
相關標籤/搜索