package com.wangbiao.generic; import java.util.ArrayList; import java.util.List; /** * @Title: GenericPrinciple.java * @Package com.wangbiao.generic * @Description: Java Generic function well at compile time ,but will be removed after compile time * @author wangbiao * @date 2014-12-18 下午5:33:36 * @version V1.0 */ public class GenericPrinciple { //this is an exception, it will compile error at compile // compile error public void print(List<String> list){ //TODO } // compile error public void print(List<Integer> list){ //TODO } public static void main(String[] args) { List list = new ArrayList(); List<String> list_string = new ArrayList<String>(); List<Integer> list_integer = new ArrayList<Integer>(); // Compiler will check the parameter type to avoid type mismatch problem in compile time //list_string.add(1234); /** * 這幾個變量字節碼都是同樣的 0 new java.util.ArrayList [16] 3 dup 4 invokespecial java.util.ArrayList() [18] 7 astore_1 [list] 8 new java.util.ArrayList [16] 11 dup 12 invokespecial java.util.ArrayList() [18] 15 astore_2 [list_string] 16 new java.util.ArrayList [16] 19 dup 20 invokespecial java.util.ArrayList() [18] 23 astore_3 [list_integer] * */ // result is true. this means generic is ignored at run time. System.out.println(list.getClass() == list_string.getClass() && list_string.getClass() == list_integer.getClass()); } }