java - 使用泛型来增加集合

标签 java generics reflection

I have to write a method that takes arguments List and int n.

Method should multiply content of given List in the same List. If n = 0, than List shoud be empty. If n = 1, List should be the same as before.

例如:

List<Integer> list = Arrays.asList(1,2,3);
multiply(list, 2);
System.out.println(list);
<小时/>

所需输出:

[1,2,3,1,2,3]

方法签名无法更改:

public static void multiply(List<?> list, int n) {

}

我尝试过这个:

public static void multiply(List<?> list, int n) {

        List<? super Object> copy = new ArrayList<>();

        if (n == 0) {
            list.clear();
        }

        for (int i = 1; i <= n; i++) {
            copy.addAll(list);         
        }

        list.clear();
        list.addAll(copy); // this is not allowed
    }

感谢您的建议!

最佳答案

不更改方法签名:

public static void multiply(List<?> list, int n) {
    if (n == 0) {
        list.clear();
        return;
    }
    @SuppressWarnings("unchecked")
    List<Object> oldSchool = (List<Object>) list;
    List<?> copy = new ArrayList<>(list);
    for (int i = 1; i < n; i++) {
        oldSchool.addAll(copy);
    }
}

(我必须将列表转换为 List<Object> )

更改签名(仅使用普通 T 作为通用参数):

public static <T> void multiply(List<T> list, int n) {
    List<T> copy = new ArrayList<>();

    if (n == 0) {
        list.clear();
    }

    for (int i = 1; i <= n; i++) {
        copy.addAll(list);
    }

    list.clear();
    list.addAll(copy); // this is now OK
}

现在,至于为什么你的原始代码没有编译:

list本质上是List<some unknown class> ,和copyList<some PARENT of that unknown class>

然后您尝试添加 copy 的内容进入list

这就像尝试转储 List<Animal> 的内容进入List<Dog> - 它们不适合,因为 List<Animal> 中可能有猫和鳄鱼

关于java - 使用泛型来增加集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363827/

相关文章:

JavaScript 反射

java - Spring Hibernate 数据库连接

java - 如何提取具有 ID 但没有子值的子元素的值?

c# - 从具有不同 <T> 的通用列表中随机选择

c# - 无法使用此代码和表达式 api 获取此属性名称

c# - 如何创建具有多个方法调用的 ExpressionTree

java - Spring动态注入(inject)一个属性

java - 无法更新 Java Swing 中的 JButton

swift - 是否可以在 Swift 中的泛型 struct init 中使用泛型?

java - 在 GWT 中创建 JSON 字符串的更好方法?