Comparator用法

2021/6/2 10:22:29

本文主要是介绍Comparator用法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Comparator  不同于 Comparable

java.util.Comparator

DEMO

----------------------------------------

Lake湖类

class Lake {
    private String name = "淡水湖";
    private String englishName = "lake";
    private int area = 1;
   
    public Lake(String n, String e, int a) {
        setName(n);
        setEnglishName(e);
        setArea(a);
    }
   
    public String getName() {
        return name;
    }
    public boolean setName(String n) {
        if(n != null && n.length() > 0) {
            name = n;
            return true;
        }
        return false;
    }
    public String getEnglishName() {
        return englishName;
    }
    public boolean setEnglishName(String e) {
        if(e != null && e.length() > 0) {
            englishName = e;
            return true;
        }
        return false;
    }
    public int getArea() {
        return area;
    }
    public boolean setArea(int a) {
        if(a >= 1 && a <= 10000) {
            area = a;
            return true;
        }
        return false;
    }
   
    public String toString() {
        return name + " (" + englishName + ", " + area + "平方公里)";
    }
}
-----------------------

按大小排序

import java.util.Comparator;

class AreaComparator implements Comparator<Lake> {
    public int compare(Lake k1, Lake k2) {
        return k1.getArea() - k2.getArea();
    }
}

-----------------------

按名字排序

import java.util.Comparator;

class NameComparator implements Comparator<Lake> {
    public int compare(Lake k1, Lake k2) {
        return k1.getEnglishName().compareTo(k2.getEnglishName());
    }
}

-----------------------

测试类

import java.util.*;

class FiveLakes {
    public static void main(String[] args) {
        ArrayList<Lake> lakes = new ArrayList<Lake>();
       
        lakes.add(new Lake("洞庭湖", "Dongting Lake", 2820));
        lakes.add(new Lake("太湖", "Lake Thai", 2250));
        lakes.add(new Lake("巢湖", "Chao Lake", 775));
        lakes.add(new Lake("鄱阳湖", "Po-yang Lake", 3914));
        lakes.add(new Lake("洪泽湖", "Hung-tse Lake", 1577));
       
        Collections.sort(lakes, new NameComparator());
        System.out.println("我国的五大淡水湖, 按\"英文名称\"[升序]排列如下:");
        for(int i = 0; i < 5; i++) {
            System.out.println(i+1 + ". " + lakes.get(i));
        }
       
        System.out.println();
        Collections.sort(lakes, new AreaComparator());
        Collections.reverse(lakes);
        System.out.println("我国的五大淡水湖, 按湖水面积[降序]排列如下:");
        for(int i = 0; i < 5; i++) {
            System.out.println(i+1 + ". " + lakes.get(i));
        }
    }
}

 



这篇关于Comparator用法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程