我有一个尝试的示例代码。代码似乎没有编译错误。为什么使用静态嵌套类节点?当我在 Node
嵌套类中删除 static
并编译时,错误显示 create generic array
in private Node[] next = new Node [R];
。到底发生了什么?
public class TrieST<Value> {
private static final int R = 256; // extended ASCII
private Node root; // root of trie
private int N; // number of keys in trie
// R-way trie node
private static class Node {
private Object val;
private Node[] next = new Node[R];
}
public TrieST() {
}
}
最佳答案
假设在您的代码片段中您使用的是非静态内部类而不是像这样的静态嵌套类:private class Node
,在这种情况下,您将尝试实例化一个 Array
这是不可能的,我们无法实例化 Array
在泛型类中,因为泛型在运行时没有关于它们类型的任何信息,而数组创建表达式指定元素类型。
所以,使用 Static Nested Class 的原因编译后,这些类是否被视为“顶级”类(就行为而言):
A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
现在,让我们考虑所有这些,然后回到编译器显示的确切错误:
Cannot create a generic array of
TrieST<Value>.Node
这意味着 array
的类型你要创建的是 TrieST<Value>.Node
其运行时的类型未知,因此可能会将不同的类型插入到 next
中大批。可以在 Cannot Create Arrays of Parameterized Types 中找到更清晰、解释更清楚的示例。
然而,静态嵌套类作为 TrieST<Value>
的内部类不表现 ,从而在 Node
中创建一个数组不会是非法的,因为它不是 TrieST<Value>.Node
类型, 它的类型是 Node
(喜欢如果它是顶级类(class))。
关于java - 为什么静态嵌套类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28467984/