| Author |
Problem with Java References
|
Pete Neu
Ranch Hand
Joined: Feb 18, 2005
Posts: 86
|
|
Hello, 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(); d1.setSomeValue(4.5) Data1 d2 = new Data2(); d2.setSomeValue(6.7) 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
Bartender
Joined: Aug 16, 2005
Posts: 12928
|
|
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 7 API documentation
Scala Notes - My blog about Scala
|
 |
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 switch(node_name) 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?
|
 |
 |
|
|
subject: Problem with Java References
|
|
|