Study/Effective-Java

[item#30] 이왕이면 제네릭 메서드로 만들라

hongeeii 2023. 11. 30. 11:43
728x90
반응형

이왕이면 제네릭 메서드로 만들라

매개변수화 타입을 받는 정적 유틸리티 메서드는 보통 제네릭임.

(Collections의 알고리즘 메서드(binarySearch, sort 등)은 모두 제네릭임)

제네릭 메서드 작성법

// 예시 코드
public static Set union(Set s1, Set s2){
  Set result = new HashSet(s1);
  result.addAll(s2);
  return result;
}

컴파일은 되지만 경고가 2개 발생.

Union.java:5: warning: [unchecked] unchecked call to
HashSet(Collection<? extends E>) as a member of raw type HashSet
  Set ressult = new HashSet(s1);

Union.java:6: warnig: [unchecked] unchecked call to
addAll(Collection<? extends E>) as a member of raw type Set
  result.addAll(s2);

경고를 없애려면 메서드를 타입 안전하게 만들어야함.

메서드 선언시 입력과 반환의 원소타입을 타입 매겨변수로 명시하고 메서드 안에서도 타입 매개변수만 사용하면 됨.

(타입 매개변수들은 선언하는)타입 매개변수 목록은 메서더의 제한자와 반환 타입 사이에 옴.

public static <E> Set<E> union(Set<E> s1, Set<E> s2){
  Set<E> resutl = new HashSet<>(s1);
  result.addAll(s2);
  return result;
}

이렇게 하면 경고없이 컴파일 되고 타입 안전하고 쓰기도 쉬움.

때때로 불변 객체를 여러 타입으로 활용할 수 있게 만들어야 할 때가 있음.

제네릭은 런타임에 타입 정보가 소거되어 하나의 객체를 어떤 타입으로든 매개변수화 할 수 있음.

하지만 이렇게 하려면 요청한 타입 매개 변수에 맞게 매번 그 객체의 타입을 바꿔주는 정적 팩터리를 만들어야함.

이런 패턴을 제네릭 싱글턴 팩터리라 하며, Collections.reverseOrder 같은 함수 객체나 Collections.emptySet 같은 컬렉션용으로 사용함.

제네릭 싱글턴 패턴

항등함수(identity function)를 담은 클래스를 만들고 싶을 때

  private static UnaryOperator<Object> IDENTITY_FN = (t) -> t;
  
  @SuppresWarnings("unchecked")
  public static <T> UnaryOperator<T> identityFunction(){
    return (UnaryOperator<T>) IDENTITY_FN;
  }

IDENTITY_FN을 UnaryOperator 로 형변환 하면 비검사 형변환 경고가 발생함.

(T가 어떤 타입이든 UnaryOperator 는 UnaryOperator가 아니기 때문)

하지만 항등함수는 입력을 그대로 반환하는 함수이기 때문에 타입 안전함.

  // 함수 사용 예시
  public static void main(String[] args){
    String[] strings = {"AA","BB","CC"};
    UnaryOperator<String> sameString = identityFunction();
    for(String s : strings)
      System.out.println(sameString.apply(s));
  }

재귀적 타입 한정(recursive type bound)

자기 자신이 들어간 표현식을 사용하여 타입 배개변수의 허용 범위를 한정 할 수 있음.

재귀적 타입 한정은 주로 타입의 자연적 순서를 정하는 Comparable 인터페이스와 함께 쓰임.

(거의 모든 타입은 자신과 같은 타입의 원소랑 비교할 수 있기 때문)

  public static <E extends Comparable<E>> E max(Collection<E> c);

타입 한정인 <E extends Comparable>는 "모든 타입 E는 자신과 비교할 수 있다" 라고 읽을 수 있음.

  public static <E extends Comparable<E>> E max(Collection<E> c){
    if(c.isempty())
      throw new IllegalArgumentException("컬렉션이 비어있습니다.");
    E result = null;
    for(E e : c){
      if(result == null || e.compareTo(result) > 0)
        result = Objects.requireNonNull(e);
    }
    return result;
  }
728x90
반응형