1 class Info<T> 2 { 3 private T var; 4 5 public T getVar() { 6 return var; 7 } 8 9 public void setVar(T var) { 10 this.var = var; 11 } 12 13 @Override 14 public String toString() { 15 return "Info [var=" + var + "]"; 16 } 17 18 } 19 20 static void fun(Info<?> in) 21 { 22 System.out.println(in.hashCode()); 23 } 24 public static void main(String[] args) 25 { 26 Info<String> info=new Info<String>(); 27 info.setVar("wfasf"); 28 fun(info); 29 } 30
Info<Integer> i1=new Info<>(); Info<String> i2=new Info<>(); Info<Integer> i3=new Info<>(); i1.setVar(20); i2.setVar("sfdsdf"); combine(i1,i3); private static<T > void combine(Info<T> i1, Info<T> i12) { System.out.println(i1.getVar()+" "+i12.getVar()); }
传递给combine的参数必须范型类型是相同的,否则编译出错。
Integer[] b=fun1(1,2,4,5,3); private static<T> T[] fun1(T... b) { return b; }
T... 可变数组