티스토리 뷰

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())
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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 29 30 31
글 보관함