So I came across some code that I thought looked kind of strange. Wanted to see what some of your opinions are of this
public class Test {
public static void main(String[] args) {
HashMap m = new HashMap();
Test2 t2 = new Test2();
t2.fill(m);
}
}
public class Test2 {
public void fill(HashMap m) {
m.put(new Integer(0), new Integer(0));
}
}
So is this code OK or should it be done another way?
Thanks
We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() .
Java is pass-byvalue only. No where it is pass-by-reference. inputMap and valueMap (copy of inputMap) are both references to the same hashmap.
You need to make a copy of the map if you want to change 1 while keeping the other the same. You can do this using the constructor which takes a map in.
This is perfectly fine since objects in java are passed by reference. If you try to assign to m directly within a method, it is wrong:
m = new HashMap();
But you can use the passed reference to modify the object passed as an argument as is the case with your sample code.
Think of it as passing the location of the object into the function. You can use this location information to fiddle with it. But since the location is just a value, assigning to the location (m
) does not have an effect on m
from where you call the function. That's why the article says the argument is passed by value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With