2014-03-12 104 views
0

我是新來的Java編程,我試圖學習如何使BST。這裏是我的代碼:如何比較對象?

類樹節點:

public void insert(Town d) { 

     if (d.compareTo(data1) < 0) //ERROR HERE 
     { 
     if (left == null) 
      left = new TreeNode(d); 
     else 
      left.insert(d); 
     } 
     else if (d.compareTo(data1) > 0) //ERROR HERE 
     { 
     if (right == null) 
      right = new TreeNode(d); 
     else 
      right.insert(d); 
     } 
    } 
} 

的錯誤是找不到符號

+8

什麼是'data1'?看起來像一個未定義的變量(因此你的問題的根本原因)。 –

+1

請發表您的其他代碼。 – tbodt

+1

將data1聲明爲有效變量。它應該是您的示例中的「城鎮」類型,以便您可以比較兩者。 – Maddy

回答

0

該錯誤告訴您沒有名爲data1的變量。從瞭解二叉樹如何工作,我建議定義一個名爲data1的成員TreeNode來保存節點的數據。你TreeNode類是這樣的:

public class TreeNode { 
    private int data1; 

    public TreeNode (int data) { 
     data1 = data; 
    } 

    public int getData() { 
     return data1; 
    } 

    public void insert(Town d) { 
     if (d.compareTo(data1) < 0) { 
      if (left == null) 
       left = new TreeNode(d); 
      else 
       left.insert(d); 
     } else if (d.compareTo(data1) > 0) { 
      if (right == null) 
       right = new TreeNode(d); 
      else 
       right.insert(d); 
     } 
    } 
} 
0

我能夠從你的問題,你打算插入到this節點的左邊或右邊的一個節點的聚集地。爲了展示我相信你打算完成的任務,我在一些不需要的地方明確使用了關鍵字this

假設每個樹節點有一個小鎮叫town

if (this.town.compareTo(d) < 0) 
{ 
    if (left == null) 
     left = new TreeNode(d); 
    else 
     left.insert(d); 
} 
else if (this.town.compareTo(d) > 0) 
{ 
    if (right == null) 
     right = new TreeNode(d); 
    else 
     right.insert(d); 
    } 
} 

其他的答案仍然是正確的 - 對您正試圖使用​​它,你提到的範圍內不存在線的標誌之一。它可能是data1,或者它可能是您的compareTo()方法。

如果城鎮是按人口排列的,則可以使用一個整齊的數學技巧來實現您的compareTo。

public int compareTo(Town other) { 
    return this.population - other.population; 
} 

或者,如果Town's按名稱排序,則可以重用String的compareTo方法。

return this.name.compareTo(other.name); 

在您必須實現更復雜的compareTo,簡單地返回一個負INT如果this小於other,如果他們是平等的,或正INT如果this大於other爲零。

0

在Town類中添加一個名爲compareTo(Datatype data1)的方法。

public class Town { 

public int compareTo(Town data1) { 

    // compare both the object and return the coresponding value 
    return 0; 
} 

}

-1

可以使用fonction .equals()上的兩個對象實現了通用的Java方法的equals()和hashCode()在Java中。

hashcode()方法用於獲取對象的整數值,equals()方法使用此散列(整數)比較並返回一個布爾值(它們是否相等)。然後,您可以比較.equals)

public void insert(Town d) { 

    if (d.equals(data1) < 0) //ERROR HERE 
    { 
    if (left == null) 
     left = new TreeNode(d); 
    else 
     left.insert(d); 
    } 
    else if (d.equals(data1) > 0) //ERROR HERE 
    { 
    if (right == null) 
     right = new TreeNode(d); 
    else 
     right.insert(d); 
    } 
} 
} 

由於數據是當然的類型城鎮的對象(。您可以使用IDE自動插入這兩種方法。

這是一個完整的解釋/例子:http://javarevisited.blogspot.ca/2011/02/how-to-write-equals-method-in-java.html

+0

中提到的定義一個compareTo mehtod在你的城市類中,而equals()返回一個布爾值,我的意思是說hashcode()用該對象創建一個散列(整數)。編輯以使其更清楚。 對不起,如果這不能回答這個問題,鑑於標題我認爲你比較的對象有困難。 – alex