当 public class aa extends ArrayList<Integer>{ }时
Foreach循环是自动调用 iterator()的,那么如果 System.out.println(new aa());是否也会自动调用呢?这又是为什么呢?

解决方案 »

  1.   

    System.out.println(new aa());
    你这里没有foreach,也没有iterator,不会调用
      

  2.   

    按楼上的说法,下面这段代码是怎么进行运行的?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));
      }
    } /* 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]
    *///:~
      

  3.   

    AbstractList包含一个 iterator 方法,但是并没有显示调用。System.out.println();从代码上看应该是调用了,不过奇怪的是 这里的size()有什么用? 
    顺便问下,如果 iterator()被调用了,那么我又定义了 hasNext() 和 next() 那么这两个方法会被自动调用吗?
      

  4.   

    AbstractCollection中的toString方法 public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append("[");        Iterator<E> i = iterator();
            boolean hasNext = i.hasNext();
            while (hasNext) {
                E o = i.next();
                buf.append(o == this ? "(this Collection)" : String.valueOf(o));
                hasNext = i.hasNext();
                if (hasNext)
                    buf.append(", ");
            } buf.append("]");
    return buf.toString();
        }
      

  5.   

    调用了,toString方法的话,又怎么能够把数据从0-29分布排列?我传进去的只是一个30。如果一般toString的话,应该输出类似 system.out.println("CountingIntegerList" + size);这样的东西
      

  6.   

    你这个toString()从哪里看的?我刚开始也以为是 toString() 但是JDK上 AbstractList 类并没有这个方法。
      

  7.   

    值是根据你的重写的size和get方法得到的.
    你单步跟踪一下就知道了.
    System.out.println()打印的是一个对象引用时,自动调用其toString()方法
      

  8.   

    public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>