passing a map into another method to be modified in java

31,257

Solution 1

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.

Solution 2

Is it OK to pass a map to a method for that method to manipulate the map? Sure.

The map is untyped; should be Map<Integer,Integer>. Use the compiler to help you get things right. Using generic types will also allow auto-boxing to be used so you can do the more succinct put(0,0).

The map should be passed as a Map, not a HashMap unless HashMap is explicitly needed (which for the case of HashMap is not going to be the case). As much as possible, use the interface, not the implementation.

The name fill looks like it's a bad name to me - it doesn't seem to "fill" anything.


As an aside, I would recommend against the magic anonymous class initialize, done so:

Map<Integer, Integer> m = new HashMap<Integer, Integer>() {{
    put(0, 0);
    }};

in favor of a simple initializer block:

Map<Integer, Integer> m = new HashMap<Integer, Integer>(); {
    m.put(0, 0);
    }

which avoids creating a redundant anonymous inner class file of the form SomeClass$n.class.

Share:
31,257
user1729409
Author by

user1729409

Updated on July 09, 2022

Comments

  • user1729409
    user1729409 almost 2 years

    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