2016-12-16 59 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