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

请教简单容器问题?
import java.util.*;
public class CountingIntegerList extends AbstractList<Integer> {
  private int size;
  public CountingIntegerList(int size){
  this.size=size<0?0:size;
  }
  public Integer get(int index){
  return Integer.valueOf(index);
  }
  public int size(){
  return size;
  }
  public static void main(String[] args) {
// TODO Auto-generated method stub
  System.out.println(new CountingIntegerList(30));//为什么此语句可以把Integer填入容器CountingIntegerList
}

}
//output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]


------解决方案--------------------
要实现不可修改的列表,程序员只需扩展AbstractList此类,并提供 get(int index) 和 size() 方法的实现。

要实现可修改的列表,程序员还必须另外重写 set(int index, Object element) 方法,否则将抛出 UnsupportedOperationException。如果列表为可变大小,则程序员必须另外重写 add(int index, Object element) 和 remove(int index) 方法。
在你的程序中并没有重写add方法和remove方法,所以它会按照默认的情况下,依照new CountingIntegerList(30)中传递的长度30 ,把0--29数字自动封装为Integer类型,并把这30个对象类型填入容器。