[Java] 지네릭스(Generics) 정리
2022. 4. 7. 23:56ㆍDev/Spring
📌 지네릭스(Generics)란?
컴파일시 타입을 체크해주는 기능으로 JDK 1.5버전부터 사용이 가능하다.
ArrayList list = new ArrayList(); // 지네릭스 도입 이전
ArrayList<Object> list = new ArrayList<Object>(); //지네릭스 도입 이후
Runtime에서 발생할 수 있는 에러를 Compile time 에러로 끌어오기 때문에 굉장히 유용하다.
📌 지네릭스 용어
Box<T> | 지네릭 클래스, 'T의 Box' 또는 'T Box'라고 읽는다. |
T | 타입 변수 또는 타입 매개변수. (T는 타입 문자) |
Box | 원시 타입(raw type) |
📌 지네릭스 장점
1. 객체의 타입 안정성을 높인다 -> Class Cast Exception을 막을 수 있다.
2. 코드가 굉장히 간결해진다.
📌 제한된 지네릭 클래스
- extends로 대입할 수 있는 타입을 제한할 수 있다. interface 또한 implements가 아닌 extends를 사용한다.
import java.util.ArrayList;
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 Ex12_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<Grape> grapeBox = new FruitBox<Apple>(); //에러. 타입 불일치
// 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의 자손이 아님
fruitBox.add(new Fruit());
}
}
class FruitBox<T extends Fruit & Eatable> extends Box<T> {}
class Box<T> {
ArrayList<T> list = new ArrayList<>(); //item을 저장할 list
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();
}
}
개인 학습 기록용이기 때문에 오류가 있을 수 있습니다.
양해 부탁드립니다🙂
📚 참고
남궁성 <자바의 정석>
'Dev > Spring' 카테고리의 다른 글
[Spring] @Transactional 정리 (0) | 2022.04.03 |
---|---|
[Spring] Log4Jdbc Log4j2 설정 방법 (0) | 2022.04.01 |
[Spring] Spring AOP (0) | 2022.03.27 |
[IntelliJ] 이클립스 스프링 프로젝트 인텔리제이로 여는 방법 (0) | 2022.03.26 |