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) { 
System.out.println(new CountingIntegerList(30)); 


这个的输出结果怎么是: 
[0,1,~~~一直到29] 我搞不懂的是: 
new CountingIntegerList(30)这个语句不是只改了size的值,而没有对元素赋值吗? 
为什么..输出结果里面有元素值?? 

解决方案 »

  1.   

    出现这种情况的原因是下边这两段代码,覆盖了父类的方法
    public Integer get(int index) { 
       return Integer.valueOf(index); 
    }
    public int size() { return size ; }  println的时候对List进行toString(),toString()内部使用Iterator迭代,而Iterator内部又使用size()来判断有多少个元素,所以会返回30个数值。同时toString()会调用get(int index)来获取元素所以实际上只是显示了index
      

  2.   

    难道在设置size 的时候 系统会自动设置各个元素的值?
      

  3.   

    倒不是设置size 的时候 系统自动设置了各个元素的值,而是如一楼所说toString()会调用get(int index)来获取元素,而楼主在覆盖父类的get()方法中的操作是:   return Integer.valueOf(index); 
    也就是返回索引值的整型值,而并不是返回List中各个元素的值,所以只是显示了size(30)个索引值。