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

  • 相关阅读:
    bits,Bytes,KB,MB,GB和TB之间的换算关系
    idea快捷键
    拦截器Interceptor和过滤器Filter的区别
    JSTL标签
    EL 表达式
    El 表达式和 Jstl 标签库
    JavaWeb servlet,乱码的原因和解决
    java类从加载、连接到初始化过程
    js中获取监听键盘事件
    ASP.NET Core Web 支付功能接入 微信-扫码支付篇(转)
  • 原文地址:https://www.cnblogs.com/hamhog/p/3832268.html
Copyright © 2011-2022 走看看