반응형
지네릭스
- 다양한 타입의 객체들을 다루는 메소드나, 컬렉션 클래스에 컴파일 시의 타입체크를 해주는 기능
- 객체의 다입을 컴파일 시에 체크하기 때문에 객체의 타입 안정성을 높이고 형변환의 번거로움이 줄어듦
- 다룰 객체의 타입을 미리 명시해줌으로써 번거로운 형변환을 줄여줆
지네릭스의 용어
ex)
class Box<T> {}
- Box<T> : 지네릭클래스
- T : 타입변수, 타입매개변수, 임의의 참조형 타입을 의미
- Box : 원시타입
Box<String> b = new Box<String>();
- <String> : 매개변수화된 타입(대입된 타입)
- Box<String> : 지네릭 타입 호출
지네릭스의 제한
- static멤버에 대해 타입 변수 T는 사용불가
- 지네릭 타입의 배열 생성 불가 ( 지네릭 배열타입의 참조변수 선언은 가능 )
지네릭클래스 객체생성과 사용
- 참조변수와 생성자에 대입된 타입이 일치해야 함
|
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
32
33
34
35
36
37
38
39
|
import java.util.ArrayList;
class Fruit { 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"; }}
// 지네릭 클래스
class Box<T> {
ArrayList<T> list = new ArrayList<>(); // ArrayList<T> list = new ArrayList<T>();와 같음
void add(T item) { list.add(item); }
T get(int i) { return list.get(i); }
int size() { return list.size(); }
public String toString() { return list.toString(); }
}
public class FruitBoxEx1 {
public static void main(String[] args) {
Box<Fruit> fruitBox = new Box<>(); // Box<Fruit> fruitBox = new Box<Fruit>();와 같음
Box<Apple> appleBox = new Box<Apple>();
Box<Toy> toyBox = new Box<Toy>();
// Box<Grape> grapeBox = new Box<Apple>(); // 에러, 타입불일치
fruitBox.add(new Fruit());
fruitBox.add(new Apple()); // ok, Apple은 Fruit의 자식이므로
appleBox.add(new Apple());
appleBox.add(new Apple());
// appleBox.add(new Toy()); // 에러, 타입불일치
toyBox.add(new Toy());
// toyBox.add(new Apple()); // 에러, 타입불일치
System.out.println(fruitBox);
System.out.println(appleBox);
System.out.println(toyBox);
}
}
|
cs |
출력
[Fruit, Apple]
[Apple, Apple]
[Toy]
'아카이브 > 자바의 정석' 카테고리의 다른 글
| 12장 지네릭스,열거형,애노테이션 20201112 (0) | 2020.11.12 |
|---|---|
| 12장 지네릭스,열거형,애노테이션 20201111 (0) | 2020.11.11 |
| 11장 컬렉션프레임워크 20201109 (0) | 2020.11.09 |
| 11장 컬렉션프레임워크 20201106 (0) | 2020.11.06 |
| 11장 컬렉션 프레임워크 20201102 (0) | 2020.11.02 |