2016-03-04 38 views
1

您好我想建立一個簡單的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方法重新分配的父對象「根」值,以指向新的項目時,出現此錯誤消息: 錯誤:(41,27)的java:不兼容的類型:com.company。 SelfSortingList.Node不能轉換到com.company.SelfSortingList.Node

所以SelfSortingList.Node不能轉換到其自己的類型?

我不知道該怎麼想此錯誤消息。將SelfSortingList和Item的類聲明更改爲「extends Comparable R」不會改變此事。

回答

2

您收到錯誤消息「R 「的類SelfSortingList

重命名內部類的類型參數(例如,「S」)和你會看到一個嘗試分配類型Item<S>(節點)到類型Item<R>(根)。

+0

謝謝。這工作 – Nabuska

0

我找到了答案我自己。 不要說:

root=(Item<R>)node; 

我不得不投它,像這樣:因爲在你的私人Item類的類型參數「R」隱藏類型參數

root=(SelfSortingList.Item)node;