Open byunghyunkim0 opened 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>
이게 뭐애요?
Set\<String> setTest = Collections.emptySet();
Set\<Integer> setTest2 = Collections.emptySet();
//setTest와 setTest2의 주소가 같은지 검증
System.out.println(setTest.hashCode() == setTest2.hashCode());
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));
}
}
Chapter : 5. 제네릭
Item : 30. 이왕이면 제네릭 메서드로 만들라
Assignee : byunghyunkim0
🍑 서론
클래스와 마찬가지로, 메서드도 제네릭으로 만들 수 있다.
🍑 본론
Unchecked call to 'HashSet(Collection<? extends E>)' as a member of raw type 'java.util.HashSet'
컴파일은 가능하지만 경고 발생
public static Set Union(Set s1, Set s2) {
Set result = new HashSet<>(s1);
result.addAll(s2);
return result;
}
}
제네릭 싱글턴 팩터리 패턴
변수에 맞게 객체의 타입을 바꿔주는 정적 팩터리를 만듬
@SuppressWarnings("unchecked") public static final Set emptySet() {
return (Set) EMPTY_SET;
}
UnsupportedOperationException
항등 함수를 구현해보자
@SuppressWarnings("unchecked") public static unaryOperator identityFunction() {
return (UnaryOperator) IDENTITY_FN; // <- SuppressWarnings가 없으면 경고 표시
}
재귀적 타입 한정
🍑 결론
Referenced by