[Java] Call by reference

이대건·2024년 9월 26일

Java

목록 보기
17/17
post-thumbnail

결론

  • 참조객체이면서 Mutable 객체는 재할당 하지 않는 이상 리턴할 필요가 없다.

참조객체란?

  • 매개변수로 전달될 때 메모리 주소가 전달된다.
  • Primitive 타입이 아닌 것

Mutable 객체란?

  • 객체의 데이터를 변경할 수 있는 객체
  • ArrayList, PriorityQueue, HashMap, 배열 등 새로운 요소를 삽입, 삭제할 수 있는 객체

왜 참조 객체이면서 Mutable 해야 하는가?

  • Wrapper 클래스는 참조 객체이지만, Immutable 하기 때문에 데이터 변경을 위해서는 리턴이 필요하다.

    • 데이터 변경시 새로운 객체를 생성해서 값을 재할당 하는 것이기 때문에

코드

1. 2차원 배열

public class CallByReferenceTest {
    public static void main(String[] args) {
        int[][] field = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        replaceArray(field);
        Arrays.stream(field).toList().forEach(ints -> {
            System.out.println(Arrays.toString(ints));
        });
    }

    private static void replaceArray(int[][] field) {
        field[0][0] = 0;
    }
}

결과

[0, 2, 3]
[4, 5, 6]
[7, 8, 9]

2. PriorityQueue

public class CallByReferenceTest {
    public static void main(String[] args) {
    	PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(1,2,3));
		pollFirstElement(pq);	
        System.out.println(pq);
    }
    public static void pollFirstElement(PriorityQueue<>() pq){
    	pq.poll();
    }
}

결과

[2, 3]
profile
일낸머스크

0개의 댓글