Play Around with Generic Collection

I currently doing some sample or experiments about generic collection, a new thing added in Java SE 5. It is very interesting but a bit complex, so I need to deep study about it.

Here is my code and the interface shown.

import java.util.*;

class Some {
    public <T> T getCode(T n) {
        return n;
    }
}

abstract class Animal<E> {
    abstract void eat(E x);
}

class Fish<E extends Animal> extends Animal<E> {
    public void eat(E x) {
        System.out.println("Fish: " + x);
    }
}

class Cat<E extends Fish> extends Animal<E> {
    public void eat(E x) {
        System.out.println("Cat: " + x);
    }
}

class Dog<E extends Animal> extends Animal<E> {
    public void eat(E x) {
        System.out.println("Dog: " + x);
    }
}

class MyEatList {
    public void addFish(List<? super Fish> list) {
        list.add(new Fish());
    }

    public void addDog(List<? super Dog> list) {
        list.add(new Dog());
    }

}

class GenericClass {
    public static void main(String args[]) {
        Some s = new Some();
        System.out.println(s.getCode(1));
        System.out.println(s.getCode("2"));
        System.out.println((s.getCode(1) instanceof Integer));
        System.out.println(s.getCode("2") instanceof String);

        Cat<Fish> c = new Cat<Fish>();
        c.eat(new Fish());

        Dog<Cat> d = new Dog<Cat>();
        d.eat(new Cat());

        List<Animal> eatList = new ArrayList<Animal>();
        MyEatList menu = new MyEatList();
        menu.addFish(eatList);
        menu.addDog(eatList);
        menu.addFish(eatList);
        menu.addDog(eatList);
        System.out.println(eatList);
    }
}

image

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.