• 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同学的指导。

  • 相关阅读:
    每日英语:Universities in Singapore strengthen cooperation with China
    每日英语:The Exercise Equivalent of a Cheeseburger?
    每日英语:Eating Safely in China, on a Budget
    每日英语:What Makes A RiskTaker
    OAuth2 vs JWT,到底怎么选?
    Docker 为什么输给了Kubernetes?Docker 员工自述!
    90 岁程序员,他的压缩算法改变了世界!
    数据库设计的 10 个最佳实践!
    代码写的垃圾被嫌弃?这 3 个插件你值得拥有!
    ShardingJdbc 实现读写分离 + 分库分表,写得太好了!
  • 原文地址:https://www.cnblogs.com/hamhog/p/3832268.html
Copyright © 2020-2023  润新知