日期:2014-05-20  浏览次数:20664 次

java如何改变已定范型?急求!!!
这是书上的一题,做不来。请高手解答!

申明一个类,此类使用私有的 ArrayList 来储存对象。使用一个Class类的引用得到第一个对象的类型之后,只允许用户插入这种类型的对象!

题目就是这样。一个标点未动!求解!

------解决方案--------------------
Java code

import java.util.ArrayList;

public class Test {
    private ArrayList<Object> arrayList;
    
    public Test() {
        arrayList = new ArrayList<Object>();
    }
    
    public boolean add(Object e) {
        if (arrayList.size() > 0) {
            if (arrayList.get(0).getClass().equals(e.getClass()))
                return arrayList.add(e);
        } else
            return arrayList.add(e);
        return false;
    }
    
    public Object get(int index) {
        return arrayList.get(index);
    }
    
    public int size() {
        return arrayList.size();
    }
    
    public static void main(String[] args) {
        Test t = new Test();
        t.add(new Integer(1));
        t.add(new Integer(2));
        t.add(new Integer(3));
        t.add(new Long(4));
        t.add(new Integer(5));
        t.add(new Boolean(false));
        t.add(new Object());
        t.add(new Integer(6));
        int loops = t.size();
        for (int i = 0; i < loops; i++)
                System.out.println(t.get(i));
    }
}