Nice review on Java generics

Tags:

http://www.ibm.com/developerworks/java/library/j-jtp07018.html

Canonical example:

public interface Box<T> {
    public T get();
    public void put(T element);
    public void put(Box<? extends T> box);

    boolean containsSame(Box<? extends T> other, 
                         EqualityComparator<? super T> comparator);

    public interface EqualityComparator<T> {
        public boolean compare(T first, T second);
    }
}

Rule of thumb:

Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don’t use a wildcard when you do both.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *