gpt4 book ai didi

Java:通用数组创建错误?

转载 作者:行者123 更新时间:2023-12-01 22:04:14 35 4
gpt4 key购买 nike

我认为在非通用数组上出现通用数组创建错误?

所以,这段代码工作得很好,非常简单。

public class test {
private subTest[] subTests;
private class subTest {

}

public test(int size) {
subTests = new subTest[size];
}
}

但我实际上想做的事情更像是这样的:

public class test<T> {
private subTest[] subTests;
private T[] arrayOfGenerics;

private class subTest {

}

public test(int size, int size2) {
arrayOfGenerics = (T[]) new Object[size]; //This line works fine
subTests = new subTest[size2]; //This line is the one giving me a 'Generic array creation' error
}
}

最佳答案

subTesttest 的内部类,因此 test 的类型参数在 subTest 内部可见。因此,您正在尝试创建一个泛型类型的数组

test<T>.subTest[]

您可以通过将类 subTest 改为静态嵌套类来解决此问题:

private static class subTest

如果这样做,数组的类型就是

test.subTest[]

关于Java:通用数组创建错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071857/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com