peaches-book-study / effective-java

이펙티브 자바 3/E
0 stars 2 forks source link

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

Open byunghyunkim0 opened 3 months ago

byunghyunkim0 commented 3 months ago

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'

제네릭 싱글턴 팩터리 패턴

@SuppressWarnings("unchecked") public static unaryOperator identityFunction() { return (UnaryOperator) IDENTITY_FN; // <- SuppressWarnings가 없으면 경고 표시 }

- 제네릭 싱글턴을 사용하는 예
```java
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));
    }
}
// 재귀적 타입 한정을 이용해 최댓값을 반환
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

hyunsoo10 commented 3 months ago
public static <E> Set<E> Union(Set<E> s1, Set<E> s2) {
        Set<E> result = new HashSet<>(s1);
        result.addAll(s2);
        return result;
    }

반환 타입이<E> Set<E>이게 뭐애요?

jseok0917 commented 3 months ago
Set\<String> setTest = Collections.emptySet();
Set\<Integer> setTest2 = Collections.emptySet();

//setTest와 setTest2의 주소가 같은지 검증
System.out.println(setTest.hashCode() == setTest2.hashCode());
youngkimi commented 3 months ago
public class Main {
    public static void main(String[] args) {
        Set<String> setString = Collections.emptySet();
        Set<Integer> setInteger = Collections.emptySet();

        System.out.println(System.identityHashCode(setInteger));
        System.out.println(System.identityHashCode(setString));
    }
}