Hi I'm trying to build a simple SelfSortingList. This is not for any real world usage so I'm doing this for learning.
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;
}
}
}
In addValue method when reassigning the the parent objects 'root' value to point to a new Item, I get this error message: Error:(41, 27) java: incompatible types: com.company.SelfSortingList.Node cannot be converted to com.company.SelfSortingList.Node
So SelfSortingList.Node cannot be converted to its own type?
I have no idea what to think of this error message. Changing the class declaration of SelfSortingList and Item to without 'extends Comparable R' does not change the matter.
You get the error message because the type parameter "R" in your private class Item
hides the type parameter "R" of the class SelfSortingList
.
Rename the type parameter of the inner class (e.g. "S") and you'll see that you try to assign the type Item<S>
(node) to the type Item<R>
(root).