Chapter 15 - Exercise 28

(4) Create a generic class Generic1 with a single method that takes an argument of type T. Create a second generic class Generic2 with a single method that returns an argument of type T. Write a generic method with a contravariant argument of the first generic class that calls its method. Write a second generic method with a covariant argument of the second generic class that calls its method. Test using the typeinfo.pets library.


Generic1是一个消费者,把T型数据往里存。Generic2是一个生产者,取出T型数据。根据PECS原则,method1用下界通配符Generic1<? super E>始终保持Generic1粒度比泛型E大,能保存E型。 method2用上界通配符Generic2<? extends E>始终保持Generic2的粒度比E小,取出的实例能向上转型成E型。

Exercise28.java



package com.ciaoshen.thinkinjava.newchapter15;
import java.util.*;

public class Exercise28 {
    private static class Generic1<T> {
        private T item;
        public Generic1(T t) {
            item = t;
        }
        public void set(T t) {
            item = t;
            System.out.println("Set " + item);
        }
    }
    private static class Generic2<T> {
        private T item;
        public Generic2(T t) {
            item = t;
        }
        public T get() {
            System.out.println("Get " + item);
            return item;
        }
    }
    private static <E> void method1(Generic1<? super E> g, E e) {
        g.set(e);
    }
    private static <E> E method2(Generic2<? extends E> g) {
        return g.get();
    }
    public static void main(String[] args) {
        TypeInfo.PetCreator creator = new TypeInfo.ForNameCreator();
        method1(new Generic1<Object>(creator.randomPet()), creator.randomPet());
        method2(new Generic2<TypeInfo.Pet>(creator.randomPet()));
    }
}



Need Java Developers? Hire Me »

I know Java. Talk is cheap, watch my code.

I live in CANADA now.