zoukankan      html  css  js  c++  java
  • Java泛型的一点用法(转)

    1、一个优秀的泛型,建议不要这样写
    public static <K, V> Map<K, V> getMap(String source, String firstSplit, String secondSplit)

    建议可以这样写
    public static <K, V> Map<K, V> getMap(List<K> keys, List<V> values)
    或类似
    public class MapItem<K, V>
    {
    public K key;
    public V value;
    }
    public static <K, V> Map<K, V> getMap(List<MapItem<K, V>> items)

    也就是即然你是泛型,你就泛吧,最好不要混用。即然混用了,“泛”就失去意义了,那还是议直接一点

    public static Map<String, Integer> getMap(String source, String firstSplit, String secondSplit) {

    Map<String, Integer> result = new HashMap<String, Integer>();
    if (source.equals("")) {
    return result;
    }
    String[] strings = source.split(firstSplit);
    for (int i = 0; i < strings.length; i++) {
    String[] tmp = strings[i].split(secondSplit);
    if (tmp.length == 2) {
    result.put(tmp[0], Integer.parseInt(tmp[1])); 
    }
    }

    return result;
    }

    2、泛型一般具有“通用”性,如果我们真想这么做,是否可以这样呢?

    //使用泛型,用于具体类型当中
    public static Map<String, Integer> getMap(String source, String firstSplit, String secondSplit){
    String[] strings = source.split(firstSplit);
    ArrayList<MapItem<String, Integer>> items = new ArrayList<MapItem<String, Integer>>();
    for (int i = 0; i < strings.length; i++) {
    String[] tmp = strings[i].split(secondSplit);
    if (tmp.length == 2) {
    MapItem<String, Integer> item = new MapItem<String, Integer>();
    item.key = tmp[0];
    item.value = Integer.parseInt(tmp[1]);
    items.add(item); 
    }
    }
    return toMap(items);
    }

    //使用泛形,以提供通用性封装
    public static <K, V> Map<K, V> toMap(List<MapItem<K,V>> items){ 
    Map<K, V> result = new HashMap<K, V>();
    for (MapItem<K, V> item : items) {
    result.put(item.key, item.value);
    }

    3、有时候一个东西总感觉不好用时,是不是本来我们就使用过度了或设计不足,而偏离了其本质?我个人觉得Java和C#的泛型都很好,提高了编码的效率和可复用性。

    http://www.cnblogs.com/magialmoon/p/3803114.html

  • 相关阅读:
    tensorflow 2.0 学习 (十) 拟合与过拟合问题
    tensorflow 2.0 学习 (九) tensorboard可视化功能认识
    tensorflow 2.0 学习 (八) keras模块的认识
    tensorflow 2.0 学习 (七) 反向传播代码逐步实现
    tensorflow 2.0 学习 (六) Himmelblua函数求极值
    tensorflow 2.0 学习 (五)MPG全连接网络训练与测试
    arp协议简单介绍
    Pthread spinlock自旋锁
    线程和进程状态
    内核态(内核空间)和用户态(用户空间)的区别和联系·
  • 原文地址:https://www.cnblogs.com/softidea/p/4110306.html
Copyright © 2011-2022 走看看