1. 제한된 지네릭 클래스
- extends로 대입할 수 있는 타입을 제한
class FruitBox<T extends Fruit> { // Fruit의 자손만 타입으로 지정가능
ArrayList<T> list = new ArrayList<T>();
}
FruitBox<Apple> appleBox = new FruitBox<Apple>(); // OK
FruixBox<Toy> toyBox = new FruitBox<Toy>(); // 에러 Toy는 Fruit의 자손이 아님
- 인터페이스인 경우에도 extends를 사용
interface Eatable { }
class FruitBox<T extends Eatable> { }
2. 예제
class Fruit implements Eatable{
public String toString() { return "Fruit"; }
}
class Apple extends Fruit { public String toString() { return "Apple"; }}
class Grape extends Fruit { public String toString() { return "Grape"; }}
class Toy { public String toString() { return "Toy"; }}
interface Eatable{}
public class Ex09_3 {
public static void main(String[] args) {
FruitBox<Fruit> fruitBox = new FruitBox<Fruit>();
FruitBox<Apple> appleBox = new FruitBox<Apple>();
FruitBox<Grape> grapeBox = new FruitBox<Grape>();
// FruitBox<Toy> toyBox = new FruitBox<Toy>(); 에러
fruitBox.add(new Fruit());
fruitBox.add(new Apple());
fruitBox.add(new Grape());
appleBox.add(new Apple());
// appleBox.add(new Grape()); // 에러 Grape는 Apple의 자손이 아님
grapeBox.add(new Grape());
System.out.println("fruitBox-"+fruitBox); // fruitBox-[Fruit, Apple, Grape]
System.out.println("appleBox-"+appleBox); // appleBox-[Apple]
System.out.println("grapeBox-"+grapeBox); // grapeBox-[Grape]
}
}
// interface를 같이 쓸때는 &사용
class FruitBox<T extends Fruit & Eatable> extends Box<T> {}
class Box<T> {
ArrayList<T> list = new ArrayList<T>();
void add (T f) { list.add(f); }
T get(int i) { return list.get(i); }
int size() { return list.size(); }
public String toString() { return list.toString(); }
}
3. 지네릭스의 제약
- 타입 변수에 대입은 인스턴스 별로 다르게 가능
Box<Apple> appleBox = new Box<Apple>(); // OK Apple객체만 저장가능
Box<Grape> grapeBox = new Box<Grape>(); // OK Grape객체만 저장가능
- static멤버에 타입 변수 사용 불가
class Box<T> {
static T item; // 에러
static int compare(T t1, T t2) { ... } // 에러
}
- 배열 생성할 때 타입 변수 사용불가. 타입 변수로 배열 선언은 가능
class Box<T> {
T[] itemArr; // OK T타입의 배열을 위한 참조변수
T[] toArray() {
T[] tmpArr = new T[itempArr.length]; // 에러 지네릭 배열 생성불가
}
}
'Java' 카테고리의 다른 글
120. 지네릭형변환 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.03 |
---|---|
119. 와일드카드, 지네릭 메서드 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.03 |
117. Iterator, HashMap과 지네릭스 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.03 |
116. 지네릭스의 용어, 지네릭스의 타입과 다형성 - 패스트캠퍼스 백엔드 부트캠프 3기 (2) | 2025.01.03 |
115. 타입 변수 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.03 |