您可以:
[更新]
以下是重写代码的四种不同方法。它们都编译。我认为您应该考虑使用一个(请参阅下面的版本4)。EnumMap
版本 1:在内部类中使用不同名称的类型参数。您需要使用 List 而不是数组。
public class TernarySearchTree<T> {
protected class TSTNode<U> {
// index values for accessing relatives array:
protected static final int PARENT = 0, LOKID = 1, EQKID = 2, HIKID = 3;
protected char splitchar;
protected List<TSTNode<U>> relatives;
private U data;
protected TSTNode(char splitchar, TSTNode<U> parent) {
this.splitchar = splitchar;
relatives = new ArrayList<TSTNode<U>>();
for (int i = 0; i < HIKID; ++i) { // Allocate 4 slots in relatives
relatives.add(null);
}
relatives.set(PARENT, parent);
}
}
private TSTNode<T> node; // When you use it, pass T as U
public TernarySearchTree() {
node = new TSTNode<T>(',', null); // When you use it, pass T as U
}
}
版本 2:从封闭类继承 T
public class TernarySearchTree<T> {
protected class TSTNode {
// index values for accessing relatives array:
protected static final int PARENT = 0, LOKID = 1, EQKID = 2, HIKID = 3;
protected char splitchar;
protected List<TSTNode> relatives;
private T data;
protected TSTNode(char splitchar, TSTNode parent) {
this.splitchar = splitchar;
relatives = new ArrayList<TSTNode>();
for (int i = 0; i < HIKID; ++i) { // Allocate 4 slots in relatives
relatives.add(null);
}
relatives.set(PARENT, parent);
}
}
private TSTNode node;
public TernarySearchTree() {
node = new TSTNode(',', null);
}
}
版本 3:使用地图(而不是列表)
public class TernarySearchTree<T> {
protected class TSTNode {
// index values for accessing relatives array:
protected static final int PARENT = 0, LOKID = 1, EQKID = 2, HIKID = 3;
protected char splitchar;
protected Map<Integer, TSTNode> relatives;
private T data;
protected TSTNode(char splitchar, TSTNode parent) {
this.splitchar = splitchar;
// Create a hash map. No need to pre-allocate!
relatives = new HashMap<Integer, TSTNode>();
relatives.put(PARENT, parent); // set -> put
}
}
private TSTNode node;
public TernarySearchTree() {
node = new TSTNode(',', null);
}
}
}
版本 4:将索引定义为枚举 + 使用 EnunMap(而不是哈希映射)
public class TernarySearchTree<T> {
protected static enum Index {
PARENT, LOKID, EQKID, HIKID;
}
protected class TSTNode {
protected char splitchar;
protected EnumMap<Index, TSTNode> relatives;
private T data;
protected TSTNode(char splitchar, TSTNode parent) {
this.splitchar = splitchar;
// Create an EnumMap.
relatives = new EnumMap<Index, TSTNode>(Index.class);
relatives.put(Index.PARENT, parent);
}
}
private TSTNode node;
public TernarySearchTree() {
node = new TSTNode(',', null);
}
}
[更新 2]要记住的一件事是:使用EnumMap而不是序号索引