카테고리 없음
[effective_java] --- generic ---
extra_
2023. 1. 8. 19:19
- item 30의 재귀적 한정타입을 사용한 max메서드
package effectivejava.chapter5.item30;
import java.util.*;
// Using a recursive type bound to express mutual comparability (Pages 137-8)
public class RecursiveTypeBound {
// Returns max value in a collection - uses recursive type bound
public static <E extends Comparable<E>> E max(Collection<E> c) {
if (c.isEmpty())
throw new IllegalArgumentException("Empty collection");
E result = null;
for (E e : c)
if (result == null || e.compareTo(result) > 0)
result = Objects.requireNonNull(e);
return result;
}
public static void main(String[] args) {
List<String> argList = Arrays.asList(args);
System.out.println(max(argList));
}
}
- item 31에서 다루고 있는 한정적 와일드 카드
package effectivejava.chapter5.item30;
import java.util.*;
// Generic union method and program to exercise it (Pages 135-6)
public class Union {
// Generic method
public static <E> Set<E> union(Set<E> s1, Set<E> s2) {
Set<E> result = new HashSet<>(s1);
result.addAll(s2);
return result;
}
// Simple program to exercise generic method
public static void main(String[] args) {
Set<String> guys = Set.of("Tom", "Dick", "Harry");
Set<String> stooges = Set.of("Larry", "Moe", "Curly");
Set<String> aflCio = union(guys, stooges);
System.out.println(aflCio);
}
}