i am new to Java and was wondering if it is possible to update dictionary's values outside of the dictionary itself. I think i loose a connection to my 'nodesIncluded' set by creating a new instance in the 'process' method in ID2. Is there any neat way to always keep track of the object underneath the value in a dictionary.
Sorry guys, i initially pasted the wrong bit of code :)
public class Dictionary {
@AllArgsConstructor
private class Info {
private Double average;
private Set nodesIncluded;
}
private void initialize(){
Map<String, Info> testDict = new HashMap<String, Info>(){{
put("ID001", new Info(1.0d, new HashSet<>(Arrays.asList("a", "b"))));
put("ID002", null);
}};
Info takenOut01 = testDict.get("ID001");
Info takenOut02 = testDict.get("ID002");
process(takenOut01, "c");
process(takenOut02, "c");
System.out.print(testDict.get("ID001").nodesIncluded.contains("c")); // true
System.out.print(testDict.get("ID002").nodesIncluded.contains("c")); // NullPointerException
System.out.print(testDict.get("ID002").nodesIncluded.contains("default")); // NullPointerException
}
private void process (Info takenOut, String newValue ) {
if (takenOut == null) {
takenOut = new Info(0.0d, new HashSet<>(Arrays.asList("default")));
}
takenOut.nodesIncluded.add(newValue);
}
public static void main(String[] args) {
Dictionary test = new Dictionary();
test.initialize();
}
}
Java passes by value, but when it comes to objects, it's a little confusing. When objects are passed through a method, its reference value gets passed. This means that operations performed on the object within the method scope affects it outside of its scope.
public static class Bar {
private int num = 0;
public int getNum() { return num; }
public void setNum(int num) { this.num = num; }
}
public static void setBar5(Bar bar) {
bar.setNum(5);
System.out.println(bar.getNum()); // outputs 5
}
public static void main(String[] args) {
Bar bar = new Bar();
setBar5(bar);
System.out.println(bar.getNum());
}
In short, if you hold an object reference to an object that is also inside a Collection, any operations on it would look like you're modifying it.
Bar bar = new Bar();
List<Bar> bars = new ArrayList<>();
bars.add(bar);
bar.setNum(5);
for(Bar b : bars) {
System.out.println(b.getNum());
}
// outputs 5
If you get the object from the collection and modify it, it will also affect any variables holding onto that object.
Bar bar2 = bar;
// modifying the element in the collection
bars.get(0).setNum(4);
// Even when we modify bar, bar2 gets affected.
System.out.println(bar2.getNum()); // outputs 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.