티스토리 뷰
제네릭 메소드
자료형을 매개변수로 가지는 메소드
하나의 메소드 정의로 여러 유형의 데이터를 처리할 때 유용함
메소드 정의에서 반환형 왼편, 각 괄호 <> 안에 타입 매개변수를 가짐
- 타입 매개변수를 메소드의 반환형이나 메소드 인자의 타입으로 사용할 수 있음
- 지역 변수의 타입으로 사용할 수도 있음
1 2 3 | public static <T> T getLast(T[] a) { return a[a.length - 1]; } | cs |
인스탄스 메소드와 static 메소드 모두 제네릭 메소드로 정의 가능
제네릭 메소드를 호출할 때,타입을 명시하지 않아도 인자에 의해 추론이 가능함
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Util { public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) { return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue()); } } public class GenericsTest5 { public static void main(String args[]) { Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util.<Intege , String>compare(p1, p2); System.out.println(same); } } | cs |
제네릭 타입과 형변환
상속 관계가 있어야 상위/하위 자료형의 관계가 존재함
- Integer나 Double은 Number의 자식 클래스
- Data <Number>와 Data <Integer>는 상하위 관계가 없음
1 2 3 4 5 6 7 8 9 10 11 12 13 | classData<T> { … } class FormattedData<T> extends Data<T> {} public class GenericTypeConversion1 { public static void main(String args[]) { Data<Number> data = new Data<Number>(); data.set(new Integer(10)); data.set(new Double(10.1)); Data <Number> data1 = new Data <Integer>(); // 컴파일 오류 Data<Integer> data = new ormattedData<Integer>(); } } | cs |
Data <Integer>[ ] arrayOfData; // 오류제네릭 타입 사용 시 유의사항
기본 자료형은 타입 매개변수로 지정할 수 없음
1 | Data<int> d = new Data<>(); // 오류 | cs |
타입 매개변수로 객체 생성을 할 수 없음
1 2 3 | class Data <T> { private T t1 = new T(); } // 오류 | cs |
타입 매개변수의 타입으로 static 필드를 선언할 수 없음
1 2 3 | class Data <T> { private static T t2; } //오류 | cs |
제네릭 타입의 배열을 선언할 수 없음
1 | Data <Integer>[] arrayOfData; //오류 | cs |