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{ }