zoukankan      html  css  js  c++  java
  • 第十一章:持有对象

    Collection

      List

        ArrayList        

          indexOf, contains, remove, removeAll都会用到equals方法

          subList所产生的列表幕后就是初始列表

          retainAll方法所产生的行为依赖于equals方法

          注:看源码ArrayList是通过数组(Object[] elementData)存储数据,有一个size属性(int size)表示集合元素个数,有两个常量int DEFAULT_CAPACITY=10和Object[] EMPTY_ELEMENTDATA = {} 当初始化时elementData=EMPTY_ELEMENTDATA,即空数组,父类AbstractList有modCount属性(int modCount = 0)表示修改次数。

        迭代器

          迭代器是一个对象,它的工作是遍历并选择序列中的对象,而客户端程序员不必知道或关心该序列底层的结构。Java的Iterator只能单向移动,这个Iterator只能用来:

          1)使用方法iterator()要求容器返回一个Iterator。Iterator将准备好返回序列的第一个元素。

          2)使用next()获得序列中的下一个元素。

          3)使用hasNext()检查序列中是否还有元素。

          4)使用remove()将迭代器新近返回的元素删除。

    private static void test1() {
        List<Pet> pets = Pets.arrayList(12);
        Iterator<Pet> it = pets.iterator();
        while (it.hasNext()) {
            Pet p = it.next();
            System.out.println(p.id() + ":" + p + " ");
        }
        System.out.println();
        // A simple approach, when possible:
        for (Pet p : pets) {
            System.out.println(p.id() + ":" + p + " ");
        }
        System.out.println();
        // An Iterator can also remove elements:
        it = pets.iterator();
        for (int i = 0; i < 6; i++) {
            it.next();
            it.remove();
        }
        System.out.println(pets);
        
    }

          有了Iterator就不必为容器中元素的数量操心了,那是由hasNext()和next()关心的事情。

          如果你只是向前遍历List,并不打算修改List对象本身,那么你可以看到foreach语法会显得更加简洁。

          Iterator还可以移除有next()产生的最后一个元素,这意味着在调用remove()之前必须调用next()。

        ListIterator

          Listerator是一个更加强大的Iterator的子类。ListIterator可以双向移动,还可以产生相对于迭代器在列表中指向的当前位置的前一个和后一个元素的索引,并且可以使用set()方法替换它访问过的最后一个元素。你可以通过调用listIterator()方法产生一个指向List开始出的ListIterator,并且还可以通过调用listerator(n)方法创建一个一开始就指向列表索引为n的元素处的ListIterator。

    private static void test1() {
        List<Pet> pets = Pets.arrayList(8);
        ListIterator<Pet> it = pets.listIterator();
        while (it.hasNext()) {
            System.out.println(it.next() + ", " + it.nextIndex() + 
                    ", " + it.previousIndex() + ": ");
        }
        System.out.println();
        // Backwards:
        while (it.hasPrevious()) {
            System.out.println(it.previous().id() + " ");
        }
        System.out.println();
        System.out.println(pets);
        it = pets.listIterator(1);
        while (it.hasNext()) {
            it.next();
            it.set(Pets.randomPet());
        }
        System.out.println(pets);
    }

          注:Iterator中有curser和lastRet两个属性,分别表示游标和访问过的最后一个元素索引。源码如下:

    /**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;
    
        public boolean hasNext() {
            return cursor != size;
        }
    
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
    
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
    
            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    
    /**
     * An optimized version of AbstractList.ListItr
     */
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }
    
        public boolean hasPrevious() {
            return cursor != 0;
        }
    
        public int nextIndex() {
            return cursor;
        }
    
        public int previousIndex() {
            return cursor - 1;
        }
    
        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }
    
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
    
            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    
        public void add(E e) {
            checkForComodification();
    
            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

        LinkedList

  • 相关阅读:
    react项目中如何解决同时需要多个请求问题
    jq+ajax+bootstrap改写一个动态分页的表格
    Window7+vs2008+QT环境搭建
    mssql charindex
    解决NTLDR is missing,系统无法启动的方法
    基于三汇语音卡的呼叫中心开发(一)
    Wince 或Windows平台 C#调用Bitmap对象后资源应该如何释放
    Anki:插件开发
    java.lang.ClassNotFoundException: com.opensymphony.xwork2.util.ValueStack
    struts2中action之间的一种跳转
  • 原文地址:https://www.cnblogs.com/wtrover/p/9561559.html
Copyright © 2011-2022 走看看