| Author |
Get Original Object
|
Cecil Phillip
Ranch Hand
Joined: Nov 05, 2001
Posts: 40
|
|
If I have a class public class Node { private Object val; public Object getObj() { return this.val; } //Below will be the other accesor methods ......... } now if I have a list of Node , all with diferent objects in them, lets say a new Float() object, new Integer() Object, and a new String() Object. How can I call toString on these Objects to return the original values instead of the hasg code values, cause that is what happens when i do a x.getObj().toString()
|
 |
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4095
|
|
you need to cast it to String or Float or whatever. not sure if you can do it in one statement. this should work though. private String y; y = (String)x.getObj(); y.toString(); if you don't know the object type, there is a way to find out what it is but i forget how. someone else will know though. [ January 19, 2004: Message edited by: Randall Twede ] [ January 19, 2004: Message edited by: Randall Twede ]
|
SCJP
|
 |
John Smith
Ranch Hand
Joined: Oct 08, 2001
Posts: 2937
|
|
How can I call toString on these Objects to return the original values instead of the hasg code values There is no magic in the toString() method, -- it will do exacltly what you will tell it to do. If you don't tell anything, the toString() method of the parent class will be invoked. If the parent class happens to be Object, you will get back the name of the class, plus @, plus the hexadecimal representation of the object hash code. To get something more meningful, simply override the toString() method of your object to return the textual representation of your object as you see fit.
|
 |
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4095
|
|
Eugene, he doesnt want to do toString() on the Node object, rather on its member variable named val.
|
 |
John Smith
Ranch Hand
Joined: Oct 08, 2001
Posts: 2937
|
|
RT: he doesnt want to do toString() on the Node object, rather on its member variable named val. Ok, but that variable is an object, not a primitive. Therefore the toString() method can be overrriden and called to return a custom-defined textual representation. For example:
|
 |
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4095
|
|
i think what you are looking for is called Run-time Type Identification and is covered in chapter 12 of bruce eckel's free online book "Thinking in java" at least it was in the 2nd edition if(x instanceof Float) ((Float)x).toString(); [ January 19, 2004: Message edited by: Randall Twede ]
|
 |
Randall Twede
Ranch Hand
Joined: Oct 21, 2000
Posts: 4095
|
|
iwont post the entire chapter, but maybe this will be helpful:
|
 |
 |
|
|
subject: Get Original Object
|
|
|