Evan Kareem
Evan Kareem

Reputation: 1

Convert object to string ( java )

I have a question how to convert an object item to string , in the source code here you can see that you can input Object item as an object , however I would want the item to be converted into a string so I can equal it to a string variable . Does anybody know how to do this ?

Thank you


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

};

Upvotes: 0

Views: 172

Answers (2)

John Estess
John Estess

Reputation: 636

If you want to compare the output of the default toString() implementation inherited from Object, it will look something like this: Ex@7852e922

You could always implement a toString() method to override the default behavior. Also, instead of (String) item you could call item.toString(). Read the toString() and hashcode() methods in: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

As stated before, the classname@hashcode representation might be enough to do what you need to do.

Upvotes: 0

user3248346
user3248346

Reputation:

You use (String)item if you want to explicitly cast the type, but be careful. Ideally you should override the toString() for the class and call that instead to return a String.

Upvotes: 2

Related Questions