The moose likes Beginning Java and the fly likes Problem with Java References Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with Java References" Watch "Problem with Java References" New topic

Problem with Java References

Pete Neu
Ranch Hand

Joined: Feb 18, 2005
Posts: 86

I need to keep 2 completly different data object structures in sync. I was hoping to do this with a hash map where I keep references to some object variables.

So basically what I need is this:

Data1 d1 = new Data1();

Data1 d2 = new Data2();

HashMap h = new HashMap();
h.put("data1" , d1.SomeValue)
h.get("data1") = d2.getSomeValue

But the SomeValue variable does not get updated in the d1 object instead I just update the value in the HashMap. Is there a way to update the d1 object ?

I know there are better ways to solve this under normal circumstances. But this in a special problem becaus d2 is a tree structure and when something changes in the tree I only get the node id thus I need the hash map approach.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

You are putting the value of the d1 object in the HashMap. Try putting the d1 object itself in the HashMap instead:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Pete Neu
Ranch Hand

Joined: Feb 18, 2005
Posts: 86
This line is exactly the problem:

((Data1) h.get("data1")).setSomeValue(d2.getSomeValue());

The key "data1" should represent a node in a tree. Let's say "child3_2". Now the only chance for mapping the change of this node back to the first data object d1 is the the name "child3_2".

I cannot say call the getter method xy because I don't know which node goes to which value in the data object d1. To make matters worse the first data object has a lot of nested elements

I don't like doing a very long switch loop like this

case 1 ; d1.setSomeValue(newNodeValue);

Because this will be a very long list with more loops in it.

Any chance of doing this with reflection or something else?
I agree. Here's the link:
subject: Problem with Java References
It's not a secret anymore!