47 Comparable接口

Comparable接口:
1)此接口强行对实现它的每个类的对象进行整体排序;
2)这种排序被称为类的自然排序,类的compareTo方法被称为它的自然比较方法;
3)对于集合,通过调用Collections.sort方法进行排序;
4)对于数组,通过调用Arrays.sort方法进行排序;
5)int compareTo(T o) 方法,该对象小于、等于或大于指定对象,则分别返回负整数、零或正整数。

package com.imooc.sort;

public class Goods implements Comparable {
    private String id;//商品编号
    private String name;//商品名称
    private double price;//商品价格
    //构造方法
    public Goods(String id,String name,double price){
        this.id=id;
        this.name=name;
        this.price=price;
    }

    //getter和setter方法
    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
    public String toString(){
        return "商品编号:"+id+",商品名称:"+name+",商品价格:"+price;
    }
    @Override
    public int compareTo(Goods o) {
        // 取出商品价格
        double price1=this.getPrice();
        double price2=o.getPrice();
        int n=new Double(price2-price1).intValue();
        return n;
    }

}
package com.imooc.sort;

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

public class GoodsTest {

    public static void main(String[] args) {
        Goods g1 = new Goods("s00001", "手机", 2000);
        Goods g2 = new Goods("s00002", "冰箱", 5000);
        Goods g3 = new Goods("s00003", "电视机", 3000);
        List goodsList = new ArrayList();
        goodsList.add(g1);
        goodsList.add(g2);
        goodsList.add(g3);
        // 排序前
        System.out.println("排序前:");
        for (Goods goods : goodsList) {
            System.out.println(goods);
        }
        Collections.sort(goodsList);//这里与Comparator比较
        // 排序后
        System.out.println("排序后:");
        for (Goods goods : goodsList) {
            System.out.println(goods);
        }

    
}

你可能感兴趣的:(47 Comparable接口)