package com.test; import com.czbsit.web.result.CodeMsg; import java.util.ArrayList; import java.util.List; public class Response<T> { private int code; private String msg; private T data; private Response( T data) { this.code = 0; this.msg = "OK"; this.data = data; } private Response(CodeMsg codeMsg){ this.code=codeMsg.getCode(); this.msg=codeMsg.getMsg(); } public static <T> Response<T> success(T data){ return new Response<>(data); } public static <T> Response<T> error(CodeMsg codeMsg){ return new Response(codeMsg); } public static void main(String[] args) { // Response<String> stringResponse = new Response<String>(12);//错误 new 指定泛型类型 Response<String> stringResponse1 = new Response<String>("333");//new 指定泛型类型 ArrayList<Integer> intArr=new ArrayList<>(); intArr.add(12); intArr.add(123); ArrayList<String> strArr=new ArrayList<>(); strArr.add("aa"); strArr.add("bb"); printArrayList(intArr); printArrayList(strArr); List<Number> list1=new ArrayList<>(); List<Integer> list2 =new ArrayList<>(); List<String> list23=new ArrayList<>(); printArrayList2(list1); printArrayList2(list2); //printArrayList2(list123);//错误 } public static void printArrayList(ArrayList<?> arr){//泛型通配符?使用案例 for (int i = 0; i < arr.size(); i++) { System.out.println(arr.get(i)); } } public static void printArrayList2(List<? extends Number> arr){//泛型通配符?使用案例 只能是Number本身或子类 List<? super Number>只能是Number本身或父类 for (int i = 0; i < arr.size(); i++) { System.out.println(arr.get(i)); } } }
public interface IFanXingInter<T> { void say(T t); }
public class FanXingInterImpl implements IFanXingInter<String> {//实现类时确定泛型类型 @Override public void say(String s) { System.out.println(s); } }