嗨,我正在尝试构建一个简单的 SelfSortingList。这不适用于任何现实世界的用途,因此我这样做是为了学习。
public class SelfSortingList<R extends Comparable<R>> {
private Item<R> root;
public SelfSortingList(){
root=null;
}
public void add(R value){
if(root==null)
root=new Item<>(value, null);
else
root.addValue(value);
}
@Override
public String toString() {
return root.toString();
}
/*Inner class*/
private class Item<R extends Comparable<R>> {
private Item<R> parent, child;
private R value;
private Item(R value, Item<R> parent) {
this.value = value;
this.parent = parent;
}
protected void addValue(R other) {
if (other.compareTo(this.value) > 0) {
System.out.println("child add");
if(child!=null) {
child.addValue(other);
}else{
child = new Item<>(other, this);
}
} else {
Item<R> node = new Item<R>(other,parent);
if(this!=root) {
parent.child = node;
}else{
root= (Item<R>) node; //This is where i get trouble
}
node.child=this;
}
}
@Override
public String toString() {
String str = value.toString() + ", ";
if(child!=null)
str+=child.toString();
return str;
}
}
}
在 addValue 方法中,当重新分配父对象“root”值以指向新项目时,我收到以下错误消息: 错误:(41, 27) java: 不兼容的类型:com.company.SelfSortingList.Node 无法转换为 com.company.SelfSortingList.Node
那么SelfSortingList.Node无法转换为它自己的类型?
我不知道如何看待这个错误消息。将 SelfSortingList 和 Item 的类声明更改为不带“extends Comparable R”并不会改变问题。
最佳答案
您收到错误消息是因为您的私有(private)类中的类型参数“R” Item
隐藏类 SelfSortingList
的类型参数“R” .
重命名内部类的类型参数(例如“S”),您将看到尝试分配类型 Item<S>
(节点)为类型Item<R>
(根)。
关于java - 通用可比较内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35796637/