美文网首页
第 31 条:利用有限通配符来提升API的灵活性

第 31 条:利用有限通配符来提升API的灵活性

作者: 综合楼 | 来源:发表于2021-05-12 21:07 被阅读0次
利用有限通配符来提升API的灵活性.jpeg
// 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; 
}

相关文章

网友评论

      本文标题:第 31 条:利用有限通配符来提升API的灵活性

      本文链接:https://www.haomeiwen.com/subject/wlaedltx.html