泛型小记

import java.util.*;

/**
 *泛型参数
 */
public class New {
	/**泛型方法**/
	public static <K,V> Map<K, V> map() {
		return new HashMap<K, V>();
	}
	public static <T> List<T> list() {
		return new ArrayList<T>();
	}
}
import java.util.*;
/**编译期类型检查,运行期泛型被擦除(迁移兼容)**/
public class Client {
	public static void f(Map<Object, String> map) {};
	public static void ff(Map<Object, List<? extends Pet>> map) {};
	public static void main(String[] args) {
		/**
		 * 默认调用泛型不指定泛型类型,则默认是Object
		 * The method f(Map<Object,String>) in the type Client is not applicable for the arguments (Map<Object,Object>)
		 * f(New.map());
		 */
		/**正确**/
		f(New.<Object,String>map());
		/**
		 * The method ff(Map<Object,List<? extends Pet>>) in the type Client is not applicable for the arguments (Map<Object,List<Dog>>)
		 * ff(New.<Object,List<Dog>>map());
		 */
		List<? extends Pet> lists = new ArrayList<Dog>();
		Map<Object, List<? extends Pet>> map = New.map();
		ff(map);
	}
}
class Pet {
	
}
class Dog extends Pet{
	
}
相关文章
相关标签/搜索