Skip to content

Item 30. 이왕이면 제네릭 메서드로 만들라 #31

@byunghyunkim0

Description

@byunghyunkim0

Chapter : 5. 제네릭

Item : 30. 이왕이면 제네릭 메서드로 만들라

Assignee : byunghyunkim0


🍑 서론

클래스와 마찬가지로, 메서드도 제네릭으로 만들 수 있다.

🍑 본론

// 로 타입 사용 - 수용 불가
public static Set Union(Set s1, Set s2) {
   Set result = new HashSet(s1);
   result.addAll(s2);
   return result;
} 

Unchecked call to 'HashSet(Collection<? extends E>)' as a member of raw type 'java.util.HashSet'

  • 컴파일은 가능하지만 경고 발생
    • 경고를 없애려면 메서드를 타입 안전하게 만들어야 한다.
    1. 메서드 선언에서의 세 집합(입력 2개와 반환 1개)의 원소 타입을 타입 매개변수로 명시한다.
    2. 메서드 안에서도 이 타입 매개변수만 사용하게 수정한다.
// 제네릭 메서드
// 타입 매개변수 목록은 <E>이고 반환 타입은 Set<E>
public static <E> Set<E> Union(Set<E> s1, Set<E> s2) {
    Set<E> result = new HashSet<>(s1);
    result.addAll(s2);
    return result;
}
// 간단한 예제
public class Main {
    public static void main(String[] args) {
        Set<String> guys = Set.of("톰", "딕", "해리");
        Set<String> stooges = Set.of("래리", "모에", "컬리");
        Set<String> aflCio = Union(guys,stooges);
        System.out.println(aflCio);
    }

    public static <E> Set<E> Union(Set<E> s1, Set<E> s2) {
        Set<E> result = new HashSet<>(s1);
        result.addAll(s2);
        return result;
    }
}
  • union 메서드는 집합3개 (입력 2개, 반환 1개)의 타입이 모두 같아야함
  • 한정적 와일드카드 타입을 사용하면 더 유연하게 개선 가능 (아이템 31)

제네릭 싱글턴 팩터리 패턴

  • 불변 객체를 여러 타입으로 활용할 수 있게 만들어야 할 때가 있다.
  • 제네릭은 런타임에 타입 정보가 소거되므로 하나의 객체를 어떤 타입으로 매개변수화 할 수 있다.
  • 변수에 맞게 객체의 타입을 바꿔주는 정적 팩터리를 만듬
    • Collections.reverseOrder같은 함수 객체나 Collection.emptySet가 존재
    // Collection.emptySet
    @SuppressWarnings("rawtypes")
    public static final Set EMPTY_SET = new EmptySet<>();
    
    @SuppressWarnings("unchecked")
    public static final <T> Set<T> emptySet() {
        return (Set<T>) EMPTY_SET;
    }
    Set<String> setTest = Collections.emptySet();
    setTest.add("dd");
    System.out.println(setTest);
    • 불변 객체이기 때문에 오류가 발생 UnsupportedOperationException

항등 함수를 구현해보자

  • 자바 Function.identity를 사용하면됨 (아이템 59)
  • 입력 값을 수정 없이 그대로 반환하는 함수이기 때문에 T가 어떤 타입이든 UnaryOperator를 사용해도 타입 안전
  • 항등함수 객체는 상태가 없으니 요청할 때마다 새로 생성하는 것은 낭비
private static UnaryOperator<Object> IDENTITY_FN = (t) -> t;

@SuppressWarnings("unchecked")
public static <T> unaryOperator<T> identityFunction() {
	return (UnaryOperator<T>) IDENTITY_FN; // <- SuppressWarnings가 없으면 경고 표시
}
  • 제네릭 싱글턴을 사용하는 예
public static void main(String[] args) {
    String[] strings = { "삼베", "대마", "나일론" };
    // Function<Object, Object> sameString = Function.identity();
    UnaryOperator<String> sameString = identityFunction();
    for (String s : strings) {
        System.out.println(sameString.apply(s));
    }
    Number[] numbers = { 1, 2.0, 3L };
    UnaryOperator<Number> sameNumber = identityFunction();
    for (Number n : numbers) {
        System.out.println(sameNumber.apply(n));
    }
}
  • String, Number로 형변환을 하지 않아도 컴파일 오류나 경고가 발생하지 않는다.

재귀적 타입 한정

  • 자기 자신이 들아간 표현식을 사용하여 타입 매개변수의 허용 범위를 한정할 수 있다.
  • 주로 타입의 자연적 순서를 정하는 Comparable인터페이스와 함께 쓰임
public interface Comparable<T> {
    int compareTo(T o);
}
  • 타입 매개변수 T는 Comparable를 구현한 타입이 비교할 수 있는 원소의 타입을 정의한다.
  • 모든 타입은 자신과 같은 타입의 원소와만 비교할 수 있다.
    • String은 Comparable을 구현하고 Integer는 Comparable를 구현하는 식이다.
// 재귀적 타입 한정을 이용
// <E extends Comparable<E>> : 모든 타입 E는 자신과 비교할 수 있다.
public static <E extends Comparable<E>> E max(Collection<E> c);
// 재귀적 타입 한정을 이용해 최댓값을 반환
public static <E extends Comparable<E>> E max(Collection<E> c) {
    if (c.isEmpty())
        // Optional<E>를 반환하도록 고치는 편이 좋음.
        throw new IllegalArgumentException("컬렉션이 비어 있습니다.");
    E result = null;
    for (E e : C)
        if (result == null || e.compareTo(result) > 0)
            result = Objects.requireNonNull(e);
    return result;
}

🍑 결론

  • 클라이언트에서 입력 매개변수와 반환값을 명시적으로 형변환해야 하는 메서드보다 제네릭 메서드가 더 안전하다.

Referenced by

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions