问答详情
源自:4-6 学生选课—课程查询

Iterator<Course> it = coursesToSelect.iterator();

这个语句中的it是什么呢?是iterator的对象吗?iterator是一个接口,为什么能够声明it呢?

提问者:六代目 2015-06-15 15:43

个回答

  • 码农_鑫森淼焱垚
    2015-09-01 09:58:22

    对于集合来说,接口中的方法都是内部实现的,你可以查看AbstractList<E>中有相关声明

     public Iterator<E> iterator() {

            return new Itr();

        }

     private class Itr implements Iterator<E> {

            /**

             * Index of element to be returned by subsequent call to next.

             */

            int cursor = 0;


            /**

             * Index of element returned by most recent call to next or

             * previous.  Reset to -1 if this element is deleted by a call

             * to remove.

             */

            int lastRet = -1;


            /**

             * The modCount value that the iterator believes that the backing

             * List should have.  If this expectation is violated, the iterator

             * has detected concurrent modification.

             */

            int expectedModCount = modCount;


            public boolean hasNext() {

                return cursor != size();

            }


            public E next() {

                checkForComodification();

                try {

                    int i = cursor;

                    E next = get(i);

                    lastRet = i;

                    cursor = i + 1;

                    return next;

                } catch (IndexOutOfBoundsException e) {

                    checkForComodification();

                    throw new NoSuchElementException();

                }

            }


            public void remove() {

                if (lastRet < 0)

                    throw new IllegalStateException();

                checkForComodification();


                try {

                    AbstractList.this.remove(lastRet);

                    if (lastRet < cursor)

                        cursor--;

                    lastRet = -1;

                    expectedModCount = modCount;

                } catch (IndexOutOfBoundsException e) {

                    throw new ConcurrentModificationException();

                }

            }


            final void checkForComodification() {

                if (modCount != expectedModCount)

                    throw new ConcurrentModificationException();

            }

        }

    简单来说,就是集合内部实现Iterator接口的方法,私有的

  • RHZhunter
    2015-07-25 20:31:09

    coursesToSelect.iterator();?

     

  • 康振宁
    2015-06-15 17:22:46

    是的。一样可以对象的