zoukankan      html  css  js  c++  java
  • Java使用泛型类来提高方法的可重用性

    我的技术博客经常被流氓网站恶意爬取转载。请移步原文:http://www.cnblogs.com/hamhog/p/3832268.html,享受整齐的排版、有效的链接、正确的代码缩进、更好的阅读体验。

    背景

    为了做今天的作业,我写了一个函数,它能把HashMap的key-value pair按value排序之后返回。一开始它是这样子的:

        public static ArrayList<Map.Entry<String,Integer>> sortByValue(HashMap<String,Integer> hashMap){
            if (hashMap == null){
                throw new NullPointerException("HashMap is null");
            }
    
            ArrayList<Map.Entry<String,Integer>> entryList = new ArrayList<Map.Entry<String,Integer>>(hashMap.entrySet());
    
            Collections.sort(entryList, new Comparator<Map.Entry<String,Integer>>() {
           @Override
    public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) { return o2.getValue() - o1.getValue(); } }); return entryList; }

    但是目前这个方法只能应用于<String,Integer>的HashMap。按value排序,按理说对key的类型没有要求。如何修改这个函数,让它能接受所有类型的key呢?

    加入泛型

    改成这样:

        public static <K> ArrayList<Entry<K,Integer>> sortByValue(Map<K,Integer> hashMap){
            ArrayList<Entry<K,Integer>> entryList = new ArrayList<Entry<K,Integer>>(hashMap.entrySet());
    
            Collections.sort(entryList, new Comparator<Entry<K,Integer>>() {
                @Override
           public int compare(Entry<K,Integer> o1, Entry<K,Integer> o2) {
                    return o2.getValue() - o1.getValue();
                }
            });
    
            return entryList;
        }

    这样就可以接受key为其他类型的HashMap了。

    但是,value为什么一定要限定为Integer呢?我想把它改成,只要是实现了Comparable接口的类都能接受。

    带有接口的泛型

    改成这样:

        public static <K,V extends Comparable> ArrayList<Map.Entry<K,V>> sortByValue(HashMap<K,V> hashMap){
            if (hashMap == null){
                throw new NullPointerException("HashMap is null");
            }
    
            ArrayList<Map.Entry<K,V>> entryList = new ArrayList<Map.Entry<K,V>>(hashMap.entrySet());
    
            Collections.sort(entryList, new Comparator<Map.Entry<K,V>>() {
                @Override
                public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                    return o2.getValue().compareTo(o1.getValue());
                }
            });
    
            return entryList;
        }

    现在这个方法可重用性强多了。调用它的写法还跟原来一样:

    ArrayList<Map.Entry<String, Integer>> sortedEntryList = sortByValue(map);

    感谢@herbix同学的指导。

  • 相关阅读:
    LVS安装配置
    Ansible自动化运维工具的使用
    DHCP中继配置
    简单爬虫
    zlib1.2.8 编译小记
    varnish 4.0编译安装小记
    imdisk命令行使用及配置
    How to say all the keyboard symbols in English and Chinese
    qwt6在Windows下Qt5的编译,安装,初步使用
    4MLinux7.0 服务器配置详解 别名TheSSS
  • 原文地址:https://www.cnblogs.com/hamhog/p/3832268.html
Copyright © 2011-2022 走看看