I made the following sample to test my knowledge
import java.util.Map; public class HashMap { public static Map<String, String> useDifferentMap(Map<String, String> valueMap) { valueMap.put("lastName", "yyyy"); return valueMap; } public static void main(String[] args) { Map<String, String> inputMap = new java.util.HashMap<String, String>(); inputMap.put("firstName", "xxxx"); inputMap.put("initial", "S"); System.out.println("inputMap : 1 " + inputMap); System.out.println("changeMe : " + useDifferentMap(inputMap)); System.out.println("inputMap : 2 " + inputMap); } }
output:
original Map : 1 {initial=S, firstName=xxxx} useDifferentMap : {lastName=yyyy, initial=S, firstName=xxxx} original Map : 2 {lastName=yyyy, initial=S, firstName=xxxx}
this useDifferentMap method gets the map and changes the value and returns the same thing back. the changed map will contain the changed value, and its area is local to the useDifferentMap method.
My question is that if java is passed by value, this changed value should not be affected on the source map.
so java goes by value or goes by reference
thanks
source share