728x90
Queue에서, poll()과 remove()의 차이는 무엇인가요?
Java에서 Queue 인터페이스는 poll()과 remove()라는 두 가지 메서드를 제공합니다.
이 두 메서드는 Queue에서 요소를 제거하는 데 사용됩니다. 그러나 poll()과 remove() 사이에는 몇 가지 차이점이 있습니다.
- 요소가 없을 때 - Queue 가 비어 있는 경우
- poll() : null 반환
- remove() : NoSuchElementException 을 throw
- 요소 제거
- poll() 과 remove() 모두 Queue의 맨 앞 요소를 제거하고 반환하며 비어있을 경우 각각의 경우를 반환함
- 요소 탐색
- poll() 과 remove() 모두 Queue에서 요소를 제거하면서 해당 요소를 반환함
poll() vs remove()
poll() - Queue 에서 요소를 제거하는 경우 사용하는 경우 안전함
remove() - Queue가 비어 있는지 확인하고 예외를 처리하는 추가적인 코드가 필요하므로 사용에 주의해야함
# poll() 메서드 사용 예시
Queue<String> queue = new LinkedList<>();
queue.offer("첫 번째 요소");
queue.offer("두 번째 요소");
String element = queue.poll();
System.out.println("제거된 요소: " + element); // 출력: 제거된 요소: 첫 번째 요소
String nextElement = queue.poll();
System.out.println("제거된 요소: " + nextElement); // 출력: 제거된 요소: 두 번째 요소
String nullElement = queue.poll();
System.out.println("제거된 요소: " + nullElement); // 출력: 제거된 요소: null (Queue가 비어 있으므로 null 반환)
# remove() 메서드 사용 예시
Queue<String> queue = new LinkedList<>();
queue.offer("첫 번째 요소");
queue.offer("두 번째 요소");
String element = queue.remove();
System.out.println("제거된 요소: " + element); // 출력: 제거된 요소: 첫 번째 요소
String nextElement = queue.remove();
System.out.println("제거된 요소: " + nextElement); // 출력: 제거된 요소: 두 번째 요소
try {
String noElement = queue.remove();
System.out.println("제거된 요소: " + noElement);
} catch (NoSuchElementException e) {
System.out.println("Queue가 비어 있습니다."); // 출력: Queue가 비어 있습니다. (NoSuchElementException 발생)
}
728x90
'2.Container' 카테고리의 다른 글
Iterator (0) | 2023.07.19 |
---|---|
ArrayList 와 Vector 의 차이점 / Array와 ArrayList의 차이점 (0) | 2023.07.18 |
ArrayList, LinkedList 차이점 / Array -> List 로 전환하려면? (0) | 2023.07.14 |
HashMap vs Hashtable / HashMap vs TreeMap / HashSet (0) | 2023.07.13 |
Collection과 Collections의 차이는? / List, Set, Map의 차이점 (0) | 2023.07.12 |