2016-12-16 141 views
0

我目前正在開發一個項目,並且我被困在這一點上。基本上我想弄清楚如何比較類型:鍵入類型:Int。從代碼中,here.theKey和theKey2是Key類型,Key1以key爲參數,獲取散列碼,然後用於在名爲'here'的BST中查找相同的散列碼。我遇到的問題是我無法弄清楚如何將this.theKey的值與作爲int的key1進行比較。將int值與Java中的不同類型進行比較

這裏是方法:

public Value get(Key key) 
    { 
     int theKey1 = hash(key); 
     TreeNode here = Tree; 
     while (here != null) 
     { 
      int theKey2=here.theKey; 


      if(theKey1 < theKey2) 
      { 
      here = here.left; 
      } 
      else if(theKey1>theKey2) 
       here = here.right; 
      else 
      { 
       return here.value; 
      } 
     } 
     throw new IllegalArgumentException("Value associated with the key not found"); 
    } 

我試着使用的compareTo但由於theKey1是int類型,我得到了一個錯誤。任何幫助或指導將不勝感激。

+1

不應該這行'int theKey2 = here.theKey;'是'int theKey2 = hash(here.theKey);'? – Mritunjay

+2

'int theKey2 = hash(here.theKey);',但是究竟是在hashcode上排序的BST的關鍵點? – EJP

+0

該項目將編寫一個程序,該程序使用帶鏈接的Hashtable來處理碰撞,並使用BST代替陣列。 –

回答

0

在這裏抨擊關鍵是毫無意義的。散列表中的BST由所有具有相同散列碼的元素組成。您需要確保Key implements Comparable<Key>並使用Key.compareTo()

-1

你已經有你的手中的答案。在代碼中,您只需要輸入Key的參考文件即可獲得它們的hash。那麼爲什麼不將所有Key s轉換成它們的哈希,並在需要時比較這些哈希?

喜歡

轉換所述第一表達在while循環int theKey2=hash(here.theKey);

我也看到在代碼的另一個問題。如果循環中的ifelse if的條件評估爲true,則在執行相應的塊之後,控件將直接進入throw語句。因此該方法不會轉移到根的子節點。因此,將continue陳述作爲您的ifelse if區塊的最後一行。

+0

哈希這些特定的鍵總是會產生相同的哈希碼,這使得整個BST毫無意義。 – EJP