Java 泛型继承
我试图用Java实现一个带有任意键的递归树结构。基本上我想要的是有一个Java 泛型继承,java,generics,inheritance,tree,compiler-errors,Java,Generics,Inheritance,Tree,Compiler Errors,我试图用Java实现一个带有任意键的递归树结构。基本上我想要的是有一个树,它包含一个X和更多的(子)树,由一组Ys索引。但是,我认为由于树将用于索引只读磁盘文件中的数据,因此树本身应该是只读的。因此,为了创建它们,我创建了一个子类,MutableTree,它应该允许对树进行编辑操作 这是我的密码: public class Tree<C,K> implements Serializable { protected C content; protected java.
树
,它包含一个X
和更多的(子)树,由一组Y
s索引。但是,我认为由于树将用于索引只读磁盘文件中的数据,因此树本身应该是只读的。因此,为了创建它们,我创建了一个子类,MutableTree
,它应该允许对树进行编辑操作
这是我的密码:
public class Tree<C,K> implements Serializable {
protected C content;
protected java.util.HashMap<K, Tree<C,K>> nexts;
protected Tree () {}
public C getContent() {
return content;
}
public java.util.Iterator<K> getKeys () {
return nexts.keySet().iterator();
}
public Tree<C,K> descend(K key) {
return nexts.get(key);
}
}
}
此代码段未编译,而是选择投诉Tree.content
和Tree.nexts
受到保护。正如你所看到的,它们确实是。但是,由于MutableTree
是Tree
的子类,它不应该访问其父级的受保护字段吗
感谢您的帮助。您只能通过与代码或子类型相同类型的引用访问受保护的成员
在您的情况下也是如此,因为创建一个可变树
将允许客户端代码变异一个假定不可变的树
,您只能通过与您的代码或子类型相同的引用访问受保护的
成员
在您的情况下也一样,因为创建一个可变树
将允许客户端代码变异一个假定不可变的树
,Google Guave(或者Google Collections项目现在称为什么)难道没有一个树可以使用吗?我不知道;我再查一下。编辑:不,谢谢。这对我来说很好。您的类是否在同一个包中?Google Guave(或Google Collections项目现在称为什么)是否有一个可以使用的树;我再查一下。编辑:不,谢谢。这对我来说很好。你们的课程在同一个包中吗?
public class MutableTree<C,K> extends Tree<C,K> {
public MutableTree (Tree<C,K> par) {
super();
this.content = par.content;
this.nexts = par.nexts;
}
public MutableTree () {
super();
}
public void setContent (C c) {
this.content = c;
}
public MutableTree<C,K> addKey (K k) {
MutableTree<C,K> noo = new MutableTree<C,K>();
nexts.put(k, noo);
return noo;
}
public boolean delKey (K k) {
return (nexts.remove(k)!=null)?true:false;
}