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

转载于:https://www.cnblogs.com/hamhog/p/3832268.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值