泛型接口:
public interface Compare<T> { public Boolean sort(T[] a,T b); }
泛型类(引用lombok插件):
@Data public class MuchT <T,K,V>{ private T t; private K k; private V v; public T getT(){ return this.t; } public K getK(){ return this.k; } public V getV(){ return v; } }
泛型方法:
public class IntCompare implements Compare<Integer>{ @Override public Boolean sort(Integer[] a, Integer b) { for(int i=0;i<a.length;i++){ if(a[i]>b) return Boolean.TRUE; } return Boolean.FALSE; } public <T> T getReturn(T[] args,int x){ //泛型方法 return args[x]; } public static void main(String[] args){ MuchT<String,Integer,Boolean> m=new MuchT<>(); m.setT("String"); m.setK(111); m.setV(Boolean.TRUE); System.out.println(m.getT()); IntCompare ic=new IntCompare(); String str=ic.getReturn(new String[]{"String1","String2","String3"},2); Integer in=ic.getReturn(new Integer[]{1,2,3,4},2); } }