
왜 참조 객체이면서 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]