Java Pass By Value and Pass By Reference

This question already has an answer here:

  • Is Java “pass-by-reference” or “pass-by-value”? 79 answers

  • Java is always pass-by-value only, just that in this case, the reference of the HashMap is passed by value. The valueMap refers to the same object as the inputMap .

    That's why when you add a key-value pair using valueMap , it is reflected back in inputMap , as both are referring to the same HashMap object.

    This answer by Eng.Fouad explains this concept very nicely.


    Java is pass-by-value. But your doubt is reffering to reference, Even reference in java passed by value.

    So reference value passed, and the map gets effected.

    You confused with the term pass by value. pass by value in the sense reference passed as value.


    When useDifferentMap(inputMap) is invoked, inputMap is assigned to the parameter Map<String, String> valueMap :

    Map<String, String> valueMap = inputMap;
    

    After the assignment, the two references inputMap and valueMap now refer to the same object in the memory, and hence modifying that object via one reference, will be reflected to the other reference.

    链接地址: http://www.djcxy.com/p/86700.html

    上一篇: String文字的垃圾回收

    下一篇: Java按值传递和按引用传递