Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a map into another method to be modified in java

Tags:

java

arguments

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

like image 581
user1729409 Avatar asked Dec 14 '12 01:12

user1729409


People also ask

How do you pass a method to another method in Java?

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() .

Does Java pass maps by reference?

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.

Can we assign a map to another map?

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.


1 Answers

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.

like image 91
perreal Avatar answered Sep 30 '22 12:09

perreal