PriorityQueue, Comparator를 사용하는 방법
-
- 아래 코드의 ? 부분에 Comparator를 사용한 PriorityQueue 선언 방법을 적어주세요.
public class Solution {
public static void main(String[] args) {
// 2번째 값을 기준으로 정렬해야 함
int[][] map = new int[][]{{1, 2}, {2, 1}, {3, 2}, {2, 4}};
PriorityQueue<int[]> pq = ?;
for (int[] m : map) {
pq.add(m);
}
}
}
-
- 아래 코드의 ? 부분에 Comparator를 사용한 PriorityQueue 선언 방법을 적어주세요.
public class Solution {
private static class Node {
int from, to, cost;
public Node(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
}
public static void main(String[] args) {
PriorityQueue<Node> pq = ? ;
}
}
답 보기
-
- 아래 코드의 ? 부분에 Comparator를 사용한 PriorityQueue 선언 방법을 적어주세요.
public class Solution {
public static void main(String[] args) {
// 2번째 값을 기준으로 정렬해야 함
int[][] map = new int[][]{{1, 2}, {2, 1}, {3, 2}, {2, 4}};
// comparingDouble, comparingLong 도 존재
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[1]));
for (int[] m : map) {
pq.add(m);
}
}
}
-
- 아래 코드의 ? 부분에 Comparator를 사용한 PriorityQueue 선언 방법을 적어주세요.
public class Solution {
private static class Node {
int from, to, cost;
public Node(int from, int to, int cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
}
public static void main(String[] args) {
PriorityQueue<Node> pq = new PriorityQueue<>(Comparator.comparing(node -> node.cost));
}
}
Java는 CallByValue인가요, CallByReference인가요?
답 보기
Java는 항상 CallByValue로 동작.
Reference Type (String, Array, List, Object 등)의 경우 객체의 참조값(주소값)을 복사해서 전달 → 하지만 이건 "주소값을 복사한 것"이지, call by reference가 아님!
즉, 메서드 내에서 객체의 필드를 변경하면 원본 객체에도 영향이 있지만, 참조 자체를 변경해도 원본엔 영향이 없음
(이게 call by reference가 아닌 이유)
- 👇 아래 코드 changeName 함수와 changeName2 함수의 차이를 보면 이해가 쉬움
class User {
Long id;
String name;
public User(
final Long id,
final String name
) {
this.id = id;
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
User user = new User(1L, "홍길동");
changeName(user, "장길동");
System.out.println(user.name); // 홍길동
changeName2(user, "장길동");
System.out.println(user.name); // 장길동
}
public static void changeName(User user, String name) {
System.out.println("원래 이름 : " + user.name); // 홍길동
user = new User(user.id, name);
System.out.println("바뀐 이름 : " + user.name); // 장길동
}
public static void changeName2(User user, String name) {
System.out.println("원래 이름 : " + user.name); // 홍길동
user.name = name;
System.out.println("바뀐 이름 : " + user.name); // 장길동
}
}