Q. 다음 중 제네릭 메소드를 선언 또는 호출할 때 옳은 표현이 아닌 것을 모두 고르시오.
1) Box <String> box = new Box <String>();
2) Box <String> box = new Box <>();
3) Box <> box = new Box <String>();
4) Box <> box = <Integer> boxing(100);
5) Box <Integer> box = boxing(100);
6) Box <Integer> box = <Integer> boxing(100);
A. 3, 4
3) 빈 <> 연산자는 생성자에서 타입을 추론할 때만 사용
4) 제네릭 메소드를 호출할 때는 매개값을 보고 구체적 타입을 추정할 수 있음
제네릭에서 타입 추론이 적용되어 <>를 생략할 수 있는 곳은 생성자 호출 시!!
public static <T> void copy(List<_____> src, List<_____> dest) {
for (T item : src) {
dest.add(item);
}
}
Q. 위의 코드의 빈칸에 들어갈 내용을 PECS 원칙을 기반으로 서술하시오.
A. producer extends get, consumer super add를 따르는 PECS에 의해
src: ? extends T / dest : ? super T
src는 데이터를 제공(Produce)하므로 extends를, dest는 데이터를 소비(consume)하므로 super을 사용해야한다.
import java.util.*;
public class Main {
public static void main(String args[]) {
List <String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.add("C");
list.add(1, "A");
list.set(3, "D");
list.remove(2);
for (int i=0; i<list.size(); i++)
System.out.print(list.get(i) + " ");
}
}
Q. 위의 코드의 실행 결과를 작성하고 for문을 Iterator로 변경하여 작성해보시오.
A. A A D
Iterator <String> it = list.iterator();
while (iter.hasNext()) {
String element = it.next();
System.out.print(element + " ");
}
리스트 :
[A] -> [A, B] -> [A, B, C] -> [A, A, B, C] -> [A, A, B, D] -> [A, A, D]
Iterator을 사용하면 Collection의 원소들을 하나씩 처리하기에 더 용이하다.
public class Main {
public static <K, V> void show(Map<K, V> map) {
Set<K> keys = map.keySet();
System.out.println("Key: " + keys);
Collection<V> values = map.values();
System.out.println("Values: " + values);
Set<Map.Entry<K, V>> entrySet = map.entrySet();
System.out.println("Key : Values");
for (Entry<K, V> entry : entrySet) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
for (int i=0; i<=10; i++) {
map.put(i, "data#" + i);
}
System.out.println(map);
System.out.println(map.get(304));
map.put(304, "data#304");
map.remove(3);
map.remove(5);
map.put(5, "new#5");
System.out.println(map);
show(map);
}
}
Q. 메소드 내의 Collection values = map.values( ); 코드에서 반환 타입이 Set이 아닌 Collection인 이유는 무엇인가요?
A. Set은 중복을 허용하지 않으므로, 중복 값을 가질 수 있는 Map의 Value 목록에는 적합하지 않습니다. 따라서 중복을 허용하는 인터페이스인 Collection 타입을 사용하는 것이 옳습니다.
Q. show 메소드 내에서 Collection values = map.values( ); 를 호출했을 때, values 객체에 대해 values.add("newdata"); 를 실행할 경우 어떤 일이 발생하나요?
A. 예외가 발생한다
map.values( )가 발생하는 컬렉션은 Map의 view 이므로, key 없이 value 값만 직접 추가하는 것은 허용되지 않습니다.