2012-04-10 54 views
0

我遇到了一個方法,我寫入字符串字插入二進制樹的方法。下面的代碼是有問題的方法。基本上,如果該單詞尚不在樹中(如BinaryTreeNode),則插入該單詞,如果該單詞在樹中,則其頻率(在BinaryTreeNode內的計數變量)將增加1。我的問題是與臨時變量searchWord。將其定義爲String會產生類型不匹配,並且getFrequency()未被定義爲String類型的語句。通用類型T僅作爲佔位符存在 - 它也不起作用。因此應該將其定義爲什麼?二進制樹可變類型問題

buildBinaryTree方法:

public static void buildBinaryTree(String word) { 
    //if word is already in tree 
    if(wordTree.contains(word)) { 
     //find existing word node 
     T searchWord = wordTree.find(word); //problem here 

     //increment frequency by 1 
     searchWord.setFrequency(searchWord.getFrequency() + 1); 
    } else { 
     //add word to tree 
     System.out.println(word); 
     wordTree.addElement(word); 
    } 
} 

BinaryTreeNode構造:

/** 
* Creates a new tree node with the specified data. 
* @param obj the element that will become a part of the new tree node 
*/ 
BinaryTreeNode(T obj) { 
    element = obj; 
    left = null; 
    right = null; 
    frequency = 1; 
} 

頻率get/set方法:

/** 
* Gets the frequency. 
* @return the frequency 
*/ 
public int getFrequency() { 
    return frequency; 
} 

/** 
* Sets the frequency. 
* @param frequency the frequency to set 
*/ 
public void setFrequency(int frequency) { 
    this.frequency = frequency; 
} 
+0

getFrequency方法在哪裏定義? – 2012-04-10 03:30:19

+0

'BinaryTreeNode()'。 – lollercopter 2012-04-10 03:32:33

回答

1

聊天交談後,你應該定義一種既具有類一個Stringint您使用作爲類型以plac e在二叉樹中替換類型變量T。然後,您可以定義諸如getString()之類的方法來返回String,incrementFrequency()以將頻率添加到等。當您從二叉樹中獲取對象時,它將是調用這些方法的正確類型。

+0

這樣做後,我收到消息'類型不匹配:無法從對象轉換爲BinaryTreeNode'。我應該提到'find()'返回一個'T'類型的對象。 – lollercopter 2012-04-10 03:32:19

+0

發佈你的詞樹代碼。 – 2012-04-10 03:32:50

+0

'wordTree'是一棵二叉樹。我不確定「發佈代碼」是什麼意思,因爲它只是單行定義。你需要二叉樹類中的任何特定方法嗎? – lollercopter 2012-04-10 03:36:14