List接收或返回多种List参数类型

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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值