티스토리 뷰
Given the code fragment:
import java.util.ArrayList;
import java.util.List;
public class List81 {
public static void main(String[] args) {
List colors=new ArrayList();
colors.add("green");
colors.add("red");
colors.add("blue");
colors.add("yellow");
colors.remove(2);
colors.add(3,"cyan");
System.out.println(colors);
}
}
What is the result?
A. (green,red,yellow,cyan)
B. (green,blue,yellow,cyan)
C. (green,red,cyan,yellow)
D. An IndexOutOfBoundsException is thrown at runtime.
정답: A
2번째 인덱스가 삭제(remove) 되니 "blue"가 삭제 된다. remove가 되면 뒤에 있는 요소들은 좌측으로 이동된다.
그때 리스트를 출력해 보면
[green, red, yellow]
이렇게 나온다.
그 상태에서 3번째 인덱스에다가 "cyan"을 add 하면
[green, red, yellow, cyan]
이렇게 된다.
참고로 4번째 인덱스에다가 넣을려고 하면 IndexOutOfBoundsException이 발생한다.
[green, red, yellow]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
at java.util.ArrayList.rangeCheckForAdd(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at List81.main(List81.java:12)
참고로 List클래스의 remove 메소드는 아래와 같다.
Object java.util.List.remove(int index)
- removeE remove(int index)
Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
Parameters:index - the index of the element to be removedReturns:the element previously at the specified positionThrows:UnsupportedOperationException - if the remove operation is not supported by this listIndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
'ocajp 자격증 (Oracle Certified Associate Ja' 카테고리의 다른 글
자바 연산자 우선순위 (0) | 2020.03.01 |
---|---|
자바 ocjap 문제 해설 - Class 47 (0) | 2020.03.01 |
자바 ocjap 문제 해설 - 변수 43 (0) | 2020.03.01 |
자바 2차원 배열 (0) | 2020.02.27 |
자바 ocajp 문제 해설 - 확장 extends (0) | 2020.02.26 |
- Total
- Today
- Yesterday
- EC
- ocjap
- xe addon
- proc
- KG
- 인포믹스
- 스크래핑
- php
- MySQL
- 자바 smtp
- 프로씨
- 이클립스
- Python
- 라이믹스 모듈
- C언어
- 파싱
- C
- esql
- xe애드온
- 파이썬
- 자바
- webix
- ocajp
- XE3
- XE
- 문자열
- JDBC
- 오라클
- 플러터
- 포인터
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |