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

  • 相关阅读:
    Lambda表达式、依赖倒置
    ASP.NET vNext 概述
    Uname
    RHEL4 i386下安装rdesktop【原创】
    Taxonomy of class loader problems encountered when using Jakarta Commons Logging(转)
    How to decompile class file in Java and Eclipse
    先有的资源,能看的速度看,不能看的,抽时间看。说不定那天就真的打不开了(转)
    Google App Engine 学习和实践
    【VBA研究】VBA通过HTTP协议实现邮件轨迹跟踪查询
    js正則表達式语法
  • 原文地址:https://www.cnblogs.com/hamhog/p/3832268.html
Copyright © 2011-2022 走看看