클래스뿐만 아니라 메서드도 제네릭화를 할 수 있음
대표적인 예로 매개변수를 받는 정적 유틸리티 메서드(Collections의 알고리즘 메서드 binarySearch, sort ...)이 보통 제네릭 메서드임
public static <T extends Comparable<? super T>> void sort(List<T> list) {
list.sort(null);
}
public static <T>
int binarySearch(List<? extends Comparable<? super T>> list, T key) {
if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD)
return Collections.indexedBinarySearch(list, key);
else
return Collections.iteratorBinarySearch(list, key);
}
public static Set union(Set s1, Set s2) {
Set result = new HashSet(s1);
result.addAll(s2);
return result;
}
타입을 안전하게 만들라는 경고임
메서드 선언에서 Set의 원소 타입을 타입 매개변수로 명시하고, 메서드 안에서도 타입 매개변수만 사용하게 수정해야 함
public static <E> set<E> union(Set<E> s1, Set<E> s2) {
Set<E> result = new HashSet<>(s1);
result.addAll(s2);
return result;
}
public <T> 반환타입 메서드이름(매개변수) {
// 메서드 내용
}
제네릭은 런타임 시점에 Object 타입으로 타입이 소거됨 → 이로 인해 하나의 객체를 어떤 타입으로든 매개변수화 할 수 있음 .
이를 위해 요청한 타입에 맞게 매번 그 객체의 타입을 바꿔주는 제네릭 싱글턴을 사용할 수 있음
public class GenericFactoryMethod {
private static final Set IMMUTABLE_EMPTY_SET = Set.copyOf(new HashSet());
@SuppressWarnings("unchecked")
public static <T> Set<T> immutableEmptySet() {
return (Set<T>) IMMUTABLE_EMPTY_SET;
}
}