0

I have this code :

private MyClass myMethod(HashMap<MyEnum, String> preferences, String type){
// stuff 
preferences.put(MyEnum.enum, type); 
MyClass myClass = ExtractMyClass(preferences);
return myClass; 
}

I call this method here :

public List<MyClass> myBigClass(){
List<MyClass> myList = new ArrayList<>();
//do a lot of stuff
Map<MyEnum, String> preferences = new HashMap<>();
preferences.put(MyEnum.enum, "value0");

myList.add(myMethod(preferences, "value1")); //first call
myList.add(myMethod(preferences, "value2")); //second call
myList.add(myMethod(preferences, "value3")); //third call

return myList; 

}

In the first call, preferences contains only value0

In the second call, it contains value0" and value1

And in the third call, it has value0, value1 and value2

I want that, for the three calls, preferences should have only value0

Why does the other values stay there, even though it was added inside a method ?

Mel
  • 453
  • 1
  • 4
  • 14
  • 1
    Basically you want to understand the difference between pass-by-value and pass-by-reference; and how pass-by-value in Java still leads to the result that you are observing. See here http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value for starters ... – GhostCat Apr 08 '15 at 14:57
  • I already read that, thank you though – Mel Apr 08 '15 at 15:00

2 Answers2

3

When you pass a reference to a mutable instance (such as a Map<MyEnum, String> reference) to a method, the method can mutate the state of that instance (assuming that it has access to methods that mutate the instance).

If you wish your myMethod not to mutate the Map you are passing to it, you should pass a copy of your original Map.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Because you each time when you are passing argument in method you are not creating new objects of map you are just passing its reference so it means each time your method is getting same map.