List<?>范型,范型通配符的使用<?>,`?`是类型实参,而不是类型形参,此处的`?`和Number、String、Integer一样都是一种实际的类型,可以把`?`看成所有类型的父类。是一种真实的类型。可以解决当具体类型不确定的时候,使用通配符`?`。List<?>一般作为参数来接收外部集合,或者返回一个具体元素类型的集合。
一个应用例子:
public void test2() {
List<?> resultList;
List<ImgSearchDTO> imgSearchDTOList =(List<ImgSearchDTO>) getList("DTO");
List<ImgSearchParam> imgSearchParamList = (List<ImgSearchParam>) getList("param");
//示例1:
//范型通配符模拟-接收参数1
resultList = imgSearchDTOList;
for (Object item : resultList) {
ImgSearchDTO itemDTO = (ImgSearchDTO) item;
System.out.println(itemDTO.getRootCategory());
}
//范型通配符-模拟返回参数,并强制转换为目标类型
List<ImgSearchDTO> dtoList = (List<ImgSearchDTO>) resultList;
for (ImgSearchDTO item : dtoList) {
System.out.println(item.getRootCategory());
}
//示例2:
resultList = imgSearchParamList;
for (Object item : resultList) {
ImgSearchParam itemParam = (ImgSearchParam) item;
System.out.println(itemParam.getCategory());
}
List<ImgSearchParam> paramList = (List<ImgSearchParam>) resultList;
for (ImgSearchParam item : paramList) {
System.out.println(item.getCategory());
}
}
public static List<?> getList(String type) {
List<ImgSearchDTO> imgSearchDTOList = new ArrayList<>();
List<ImgSearchParam> imgSearchParamList = new ArrayList<>();
ImgSearchDTO imgSearchDTO1 = new ImgSearchDTO();
ImgSearchDTO imgSearchDTO2 = new ImgSearchDTO();
imgSearchDTO1.setRootCategory("DTO_test1");
imgSearchDTO2.setRootCategory("DTO_test2");
imgSearchDTOList.add(imgSearchDTO1);
imgSearchDTOList.add(imgSearchDTO2);
ImgSearchParam imgSearchParam1 = new ImgSearchParam();
ImgSearchParam imgSearchParam2 = new ImgSearchParam();
imgSearchParam1.setCategory("param_test1");
imgSearchParam2.setCategory("param_test2");
imgSearchParamList.add(imgSearchParam1);
imgSearchParamList.add(imgSearchParam2);
if (type.equals("DTO")) {
return imgSearchDTOList;
} else {
return imgSearchParamList;
}
}