반응형
Preface
대부분 기본적인 제네릭의 사용법과 관련된 문제들이므로 책의 내용만 잘 읽어봤다면 딱히 어려울 만한 문제는 없다.
- 2번
package ch13;
class Container<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
}
public class Exercise2 {
public static void main(String[] args) {
Container<String> container1 = new Container<String>();
container1.set("홍길동");
String str = container1.get();
System.out.println(str);
Container<Integer> container2 = new Container<Integer>();
container2.set(6);
int value = container2.get();
System.out.println(value);
}
}
- 3번
package ch13;
class Container1<T, M> {
private T t;
private M m;
public void set(T t, M m) {
this.t = t;
this.m = m;
}
public T getKey() {
return t;
}
public M getValue() {
return m;
}
}
public class Exercise3 {
public static void main(String[] args) {
Container1<String, String> container1 = new Container1<String, String>();
container1.set("홍길동", "도적");
String name1 = container1.getKey();
String job = container1.getValue();
System.out.println(name1 + " " + job);
Container1<String, Integer> container2 = new Container1<String, Integer>();
container2.set("홍길동", 35);
String name2 = container2.getKey();
int age = container2.getValue();
System.out.println(name2 + " " + age);
}
}
- 4번
package ch13;
class Pair2<K, V> {
private K key;
private V value;
public Pair2(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
class ChildPair<K, V> extends Pair2<K, V> {
public ChildPair(K k, V v) {
super(k, v);
}
}
class OtherPair<K, V> {
private K key;
private V value;
public OtherPair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
class Util3 {
// 방법 1
public static <K,V> V getValue(Pair2<K,V> p, K k) {
if (p.getKey() == k) {
return p.getValue();
} else {
return null;
}
}
// 방법 2
// public static <P extends Pair<K,V>, K , V> V getValue(P p, K k) {
// if (p.getKey() == k) {
// return p.getValue();
// } else {
// return null;
// }
}
public class Exercise4 {
public static void main(String[] args) {
Pair2<String, Integer> pair = new Pair2<>("홍길동", 35);
Integer age = Util3.getValue(pair, "홍길동");
System.out.println(age);
ChildPair<String, Integer> childPair = new ChildPair<>("홍삼원", 20);
Integer childAge = Util3.getValue(childPair, "홍삼순");
System.out.println(childAge);
// OtherPair<String , Integer> otherPair = new OtherPair<>("홍삼원", 20);
// int otherAge = Util.getValue(otherPair, "홍삼원");
// System.out.println(otherAge);
}
}
728x90
반응형
'Java > 이것이 자바다' 카테고리의 다른 글
이자바 14장(람다식) 확인문제 (0) | 2023.04.28 |
---|---|
람다식 (0) | 2023.04.27 |
제네릭 (0) | 2023.04.25 |
이자바 12장(멀티 스레드) 확인문제 (0) | 2023.04.25 |
멀티 스레드 (0) | 2023.04.21 |
댓글