第 31 条:利用有限通配符来提升API的灵活性
2021-05-12 本文已影响0人
综合楼

// Object-based collection - a prime candidate for generics
public class Stack<E> {
private E[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements =(E[]) new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(E e) {
ensureCapacity();
elements[size++]=e;
}
public E pop() {
if (size == 0)
throw new EmptyStackException();
E result = elements[--size];
elements[size] = null;// Eliminate obsolete reference
return result;
}
public boolean isEmpty() {
return size == 0;
}
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2* size+1);
}
public void pushAll(Iterable<? extends E> src) {
for(E e : src)
push(e);
}
public void popAll(Collection<? super E> dst) {
while(!isEmpty()) {
dst.add(pop());
}
}
public static void main(String[] args) {
Stack<Number> s = new Stack<Number>();
List<Integer> integers = new ArrayList<>(Arrays.asList(1,2));
Iterable<Integer> integerIterable = integers;
s.pushAll(integerIterable);
}
}
static <E> reduce(List<E> list , Function<E> f , E initVal)
static <E> E reduce(List<? extends E> list , Function<E> f , E initVal)
public static <E> Set<E> uniono(Set<E> s1 , Set<E> s2)
public static <E> Set<E> union(Set<? extends E> s1 , Set<? extends E> s2)
public static <T extends Comparable<T>> T max(List<T> list)
public static <T extends Comparable<? super T>> T max(List<? extends T> list)
public static <T extends Comparable<? super T>> T max(List<? extends T> list) {
Iterator<? extends T> i = list.iterator();
T result = i.next();
while (i.hasNext()) {
T t = i.next();
if (t.compareTo(result) > 0) result = t;
}
return result;
}