728x90
제네릭 Generics
다양한 타입의 객체를 다루는 메서드, 컬렉션 클래스에서 컴파일 시에 타입을 미리체크하는 것
Generic이 아닐 경우, 클래스에 모든 타입이 들어갈 수 있어 입력 시 편리하지만, 이후 클래스를 이용할 때 불편함
- 미리 사용할 타입을 명시 → 형 변환을 하지 않아도 됨
- 객체의 타입에 대한 안전성 향상 및 형 변환의 번거로움 감소
표현
클래스또는 인터페이스 선언 시 <>에 타입 파라미터 표시
타입 파라미터
- T : reference Type
- E: Element
- K : Key
- V : Value
Class_Name<Type> generic = new Class_Name<Type>();
Class_Name<String> generic2 = new Class_Name<>(); // 생성 쪽에 쓰지 않으면 알아서 같은 타입으로
Type parameter의 제한
필요에 따라 구체적인 타입 제한 필요
type parameter 선언 뒤 extends와 함께 상위 타입 명시
class Calculator<T extends Number> {
public double add(T t1, T t2) {
double result = t1.doubleValue() + t2.doubleValue();
return result;
}
}
public class GenericTest {
public static void main(String[] args) {
Calculator<Integer> cal = new Calculator<>();
cal.add(1, 2);
System.out.println(cal.add(1, 2));
}
}
인터페이스로 제한할 경우도 extends로 사용
클래스와 함께 인터페이스 제약 조건을 이용할 경우 &으로 연결
class TypeRestric2<T extends Number & Cloneable & Comparable<String>>{}
와일드 카드
generic type에서 구체적인 타입 대신 사용
- Generic type<?> 타입에 제한이 없음
- Generic type<? extends T> T 또는 T를 상속받은 타입들만 사용 가능
- Generic type<? super T> T 또는 T의 조상 타입만 사용 가능
728x90
'Java' 카테고리의 다른 글
[자바/Java] 직렬화와 역직렬화, ObjectInputStream ObjectOutputStream, Serializable (0) | 2022.07.28 |
---|---|
[자바/Java] 객체 참조 시 인터페이스 사용 이유 (0) | 2022.07.28 |
[자바/Java] 클래스 다형성(Polymorphism) (0) | 2022.07.25 |
[자바/Java] 클래스(Class), 상속, 생성자(Constructor), 오버라이딩(Override) (0) | 2022.07.25 |
[자바/Java] 싱글톤(Singleton) 패턴, Static (0) | 2022.07.25 |