2015-02-08 197 views
0

我有一個問題如何在源代碼中將對象項轉換爲字符串 這裏您可以看到您可以將對象項作爲對象輸入,但是我希望項目是轉換成一個字符串,所以我可以將它等同於一個字符串變量。 有誰知道如何做到這一點?將對象轉換爲字符串(java)

謝謝


public QueueNode AddItem (Object item, int priority) 
{ 


    PQNode newNode = new PQNode (item, priority); 
    if (root != null) { 

     spreadingOutToInsert (newNode); 

     // if newNode equals or is greater than the root then put the old root as the rightChild of the newnode 

     if (newNode.compare (root) < 0) 

     { 
      newNode.leftNode = root.leftNode; 

      newNode.right = root; 

      root.leftNode  = null; 

      // if newNode equals or is greater than the root then just put the old root as the leftChild of the newnode 
     } else 
     { 
      newNode.leftNode = root; 

      newNode.right = root.right; 

      root.right = null; 
     }; 

    }; 

    size++; 
    return root = newNode; // this is to make the newNode into the new root 

}; 
+1

你不能簡單地寫一個方法嗎?手動或[覆蓋toString()](https://stackoverflow.com/questions/10734106/how-to-override-tostring-properly-in-java)。 – Klaster 2015-02-08 22:58:32

回答

2

您使用(String)item,如果你想顯式轉換的類型,但要小心。理想情況下,您應該覆蓋該班級的toString(),然後撥打電話,返回String

+0

說什麼? '(String)item'不會轉換任何東西。它所做的一切就是告訴編譯器,「相信我,我知道'item'變量擁有對'String'的引用。」但是,如果它不持有對字符串的引用?你會得到一個運行時錯誤,這可能不是你想要的。 – 2015-02-08 23:33:51

0

如果要比較默認的toString()的輸出實現從Object繼承,它會是這個樣子:防爆@ 7852e922

你總是可以實現toString()方法來覆蓋默認行爲。此外,而不是(String)項目,你可以調用item.toString()。閱讀下面的toString()和hashcode()方法: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

如前所述,classname @ hashcode表示可能足以執行您需要執行的操作。