如果在面试中问在项目中有无用过泛型这怎么回答,怎么简洁回答

来源:3-9 思考:高频面试题(持续更新)

qq_蓝骏毅_04076633

2021-05-02

public class CopyUtil {
    /**
     * 单体复制
     */
    public static <T> T copy(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BeanUtils.copyProperties(source, obj);
        return obj;
    }

    /**
     * 列表复制
     */
    public static <T> List<T> copyList(List source, Class<T> clazz) {
        List<T> target = new ArrayList<>();
        if (!CollectionUtils.isEmpty(source)){
            for (Object c: source) {
                T obj = copy(c, clazz);
                target.add(obj);
            }
        }
        return target;
    }
}


写回答

1回答

甲蛙

2021-05-03

可以这样说:泛型用来存放一些不确定的类型的场景会用到。比如说泛型在JDK内部经常用到,常见的List、Set,都用到了泛型。在一些工具类中也会用到,比如我自己写了个CopyUtil,封装BeanUtils,因为要复制的对象不确定的,所以用到了泛型。

1
0

Spring Boot+Vue3前后端分离,实战wiki知识库系统

一课掌握前后端最火框架,更有职场竞争力

2524 学习 · 1671 问题

查看课程