It's lonely in the lab by yourself...

Dec 20, 2007 16:07

Java: "Everything is an Object! I'm pass by reference ( Read more... )

Leave a comment

Comments 7

rebelliousuno December 21 2007, 08:31:10 UTC
generics are ur friend :)
then theres arraylist which is a simple list collection and enum as well those are first thoughgts I can look at jdocs when I more awake

Reply


rebelliousuno December 21 2007, 14:40:09 UTC
So now that I'm more awake you want a list of Key Value pairs
where

Key :: String
Value :: int/double

If thats the case then Java HashMap is probably what you want

Now unfortunatly you want to be able to store doubles and ints...so I'd make things easier by just storing doubles for the time being...as you know Java has the wrapper objects for int and double known as Integer and Double so I'd make a hash map of String to Double

After Java 5 they introduced generics into the collections

So you can decalre

HashMap map = new HashMap(); (you might actually be able to say and use Java Reflections to test what type of Number you have Integer/Double...although Number has get intValue floatValue etc...so they should work...)

Then when ever you call get(key) you wont get an object back you'll get a Double so no need to cast or anything

(this also works for arraylists etc)

Reply

rebelliousuno December 21 2007, 14:41:33 UTC
also it seems to have hated my post a bit there...whoopsee

Reply

highbulp December 21 2007, 15:25:16 UTC
That's exactly what I'm doing. The problem is, when I grab a reference to a key in the HashMap, Java converts it from an Object to a primitive. Primitives are pass by value, so when I try and change the value of that primitive, it doesn't change the value in the Map.

The problem is that this:

myVar = map.get(key);
System.out.println(myVar==map.get(key)); //Prints "true"--they are the same reference
myVar = myVar + 1;
System.out.println(myVar==map.get(key)); //Prints "false"--they are no longer the same reference.

I can look through the API some more, but I'm not sure there is a way to apply arithmetic to a Double object and have it remain a Double object.

Thinking about it, I wonder if I can change the value of the key in the HashMap entry and then have it work... hmm.. must try. If not, I'm afraid I'm going to have to create my own wrapper class that Java won't convert to a primitive.

Reply

rebelliousuno December 21 2007, 15:36:46 UTC
Problem there is you're adding +1 to an Object
which well doesn't really make sense

You'd have to create a new Double

ie myVar = myVar.doubleValue()+1;

Though that doesn't get around the fact that myVar != map.get(key)
but if you were then wanting to reset map.get(key) to the new value its a case of setting it back...long winded perhaps

but its the same as map.set(key,new Double(map.get(key).doubleValue()+1));

if thats what you're trying to do?

Perhaps I'm miss understanding a bit what you're trying to accomplish

Reply


Leave a comment

Up