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

原文地址:https://www.cnblogs.com/softidea/p/4110306.html