Hello everyone: I'm having trouble pulling a value out of my Set collection. Instead of the value I get a reference like: java146.util.Counter@cfb549 What I'm looking for is a numeric value not the reference. I tried type casting: pw.println(me.getKey()+":"+"\t"+((Counter)me.getValue())); however I still got the reference as the value. Any suggestions?
All the container classes only hold Objects. They cannot directly hold built-in types like int or double. To store these native types, you must use the wrapper classes like Integer and Double. So to get teh value that is stored, you have to cast to the appropriate container class and then use the approperiate member function to get the value. Check the API docs for more information about the wrapper classes. HTH Layne
I'm assuming the me object is of type Map.Entry. so me.getValue() is an Object that must be cast to a Counter: (Counter)(me.getValue()) Then you want to use the toString() or some getValue() method to get at the required attribute of Counter: ((Counter)(me.getValue())).toString() or ((Counter)(me.getValue())).getValue() By the way have I seen this Counter class somewhere?
Thanks Layne and Barry: I figured it out! I wasn't calling the getOccurance method in my Counter object. (Duh!) So the code i had was correct only missing one key part.(the method call) now my project is complete! Thanks again, Chad
Then you want to use the toString() or some getValue() method to get at the required attribute of Counter: In fact, toString() was being called implicitly by the original code: pw.println(me.getKey()+":"+"\t"+((Counter)me.getValue())); String concatenation (+) on an Object automatically invokes toString() if the Object is not already a String. So you may find it useful to add a toString() method to your Counter class which gives you the desired output:
Now anytime you include a Counter object in a print statement, it will convert to a meaningful String rather than the ugly serial-number-type thing which you inherit by default from the Object class.
Post by:autobot
catch it before it slithers away! Oh wait, it's a tiny ad:
a bit of art, as a gift, that will fit in a stocking