从Java中TreeMap集合来引出外部比较器和内部比较器的一些用法

从Java中TreeMap集合来引出外部比较器和内部比较器的一些用法,第1张

从Java中TreeMap集合来引出外部比较器和内部比较器的一些用法 从Java中TreeMap集合来引出外部比较器和内部比较器的一些用法

引出:从TreeMap的put方法中来看

在往TreeMao集合里添加元素的时候,会进行比较添加元素的key值,这时就会用到比较器,在源码中有两种比较器。

将元素的key值进行比较,调用key值自己的compareTo 这有两种情况:

[1] key值自己是系统定义好的,像Integer、String等,那么Integer或String本身自带compareTo方法,然后来进行比较

从代码中看

public class Test01 {
    public static void main(String[] args) {
        //这里的key是String它自身带了比较器即比较的方法,因此不需要自己来弄比较器
        TreeMap treeMap = new TreeMap<>();
        treeMap.put("Tom",101);
        treeMap.put("Confidence",101);
        treeMap.put("Excellent",101);
        treeMap.put("Apple",101);
        treeMap.put("Google",101);
        System.out.println(treeMap);
    }
}

(2)自定义类实现Comparator接口,这种被称为外部比较器,在创建TreeMap集合对象时需要往参数里添加比较器的对象

从代码来看方法一:

public class Student {
//为了节约空间,这个类在这里只显示了它的属性
    private int Std;
    private String name;
}
//自己定义一个比较类名字为CompareName
class CompareName implements Comparator{
    //这个类实现了Comparator接口,它是一个外部比较器的接口,
    //如下面方法所示,这个compare方法用来比较传进参数的两个Student对象的name属性
    @Override
    public int compare(Student o1, Student o2) {
        return o1.getName().compareTo(o2.getName());
    }
}
public class Test01 {
    public static void main(String[] args) {
        //创建比较类的对象
        CompareName cn = new CompareName();
        //在创建对象时,传入比较类的对象,因为到时候要调用这个比较类对象里的比较方法
        TreeMap map = new TreeMap<>(cn);
        map.put((new Student(105,"Tom")),103);
        map.put((new Student(103,"Cat")),103);
        map.put((new Student(102,"Excellent")),104);
        map.put((new Student(108,"Legend")),106);
        map.put((new Student(108,"Apple")),106);
        System.out.println(map);
    }
}

可能会有个疑问,为啥在创建TreeMap集合对象时可以传进自己定义那个类的对象呢?
下面我们从源码来看:

方法二:其实跟方法一差不多 只不过是在定义 比较类的时候直接在创建TreeMap集合对象那里进行 *** 作,如下面代码所示:

public class Student {
//为了节约空间,这个类在这里只显示了它的属性
    private int Std;
    private String name;
}
import java.util.Comparator;
import java.util.TreeMap;

public class Test01 {
    public static void main(String[] args) {
    
        TreeMap map = new TreeMap<>(new Comparator() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        map.put((new Student(105,"Tom")),103);
        map.put((new Student(103,"Cat")),103);
        map.put((new Student(102,"Excellent")),104);
        map.put((new Student(108,"Legend")),106);
        map.put((new Student(108,"Apple")),106);
        System.out.println(map);
    }
}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5707140.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存