컴퓨터공부/Kotlin & Java

HashMap은 call by reference를 사용한다.

achivenKakao 2023. 12. 6. 14:17
  • HashMap의 리턴 값은 call by ref를 사용하기 때문에, 값을 변경하여도 다시 put을 사용하지 않아도 된다.
  • In this example, the StringBuilder object is modified directly after being retrieved from the HashMap, and the changes are reflected in the value stored in the map. Note that you don't need to use the put method again to update the value in the map because you are working with a reference to the same object.

 

public class HashMapExample {
    public static void main(String[] args) {
        Map<String, StringBuilder> map = new HashMap<>();

        // Creating a StringBuilder and putting it in the map
        StringBuilder sb = new StringBuilder("Hello");
        map.put("key", sb);

        // Modifying the StringBuilder directly
        sb.append(", World!");

        // Retrieving the StringBuilder from the map
        StringBuilder retrievedValue = map.get("key");

        // Printing the modified value
        System.out.println(retrievedValue.toString()); // Output: Hello, World!
    }
}