Java容器

Iterable是一个超级接口,被Collection继承,只有一个方法,返回一个迭代器。

迭代器

迭代器是指一种设计模式,是一个对象,可以遍历选择序列中的对象,开发人员不需要了解序列的结构(hasNext就next循环遍历)。

迭代器通常被称为轻量级对象,因为创建它的代价小。(不清楚是什么逻辑,如果是使用内部类实现了Iterable接口定制集合的迭代器功能,以及逻辑也比较简单清晰)

举个栗子

  拿ArrayList来说,iterator()实现的是创建了一个权限私有的内部类对象,该内部类实现迭代器Iterable接口,根据对应的集合去设计方法。

    //重写方法返回一个迭代器内部类对象
    public Iterator<E> iterator() {
        return new Itr();
    }

    //
   private class Itr implements Iterator<E> {
        int cursor;       // 要返回的下一个元素的索引
        int lastRet = -1; // 返回的元素的索引; -1 如果没有的话
        int expectedModCount = modCount;//该集合进行修改次数 (用于读取net(),移除元素remove()时与集合进行比较,判断是否有并发修改异常)

        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();
        }
    }

使用迭代器遍历集合

        List<String> arrayList = new ArrayList<>();
        arrayList.add("张三");
        arrayList.add("李四");
        Iterator listIter = arrayList.iterator();
        while(listIter.hasNext()){
            System.out.println(listIter.next());
        }

 

List 接口

  list是有序的集合(也称为序列)。此接口的用户可以对列表中每个元素的插入位置进行精确地控制(set方法)。用户可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素(get方法)。

  它与Set不同,list运行插入重复元素。

  list提供了除了迭代器以外的特殊迭代器ListIterator,除了允许 Iterator 接口提供的正常操作外,该迭代器还允许元素插入和替换,以及双向访问。还提供了一个方法(如下)来获取从列表中指定位置开始的列表迭代器。

  例如在ArrayList中,ListItr内部类继承内部类Itr实现了特殊迭代器ListIterator。

    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) {//更新当前迭代器返回过得索引元素,也就是使用add或者remove之后,返回过得索引会被重置(因为元素结构发生变化了嘛)
            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();
            }
        }
    }

 

List子类

  ArrayList,LinkedList,Vector。

  ArrayLis是基于数组实现的List类,它封装了一个动态的、增长的、允许再分配的Object[ ]数组.它允许对元素进行快速随机访问

  当从ArrayList的中间位置插入或者删除元素时,需要对数组进行复制、移动、代价比较高。因此,它适合随机查找和遍历,不适合插入和删除。

  

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  //数组大小变更操作以及判断是否需要变更
        elementData[size++] = e;//将元素添加到数组里面完成新增
        return true;
    }

   private void ensureCapacityInternal(int minCapacity) {
        if (elementData == EMPTY_ELEMENTDATA) {//如果数组是空的,默认10个和变更后元素个数作比较,哪个大用哪个
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    
     private void ensureExplicitCapacity(int minCapacity) {
        modCount++;//集合操作次数更新

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)//不超过10个不给变更
            grow(minCapacity);
    }

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);//右移1位加上原先的值,新增50%
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);//变更数组长度
    }

另外如果以集合为构造参数 public ArrayList(Collection<? extends E> c)  时,c.toArray()返回的数组对象的长度是传入集合的size,并不是传入集合的数组大小,这个需要查看toArray里面做了啥。另外需要注意的是这样构建的集合,数组大小和集合size是等同,再次add(),添加元素的时候,进行检测是否需要扩容。

public class ArraryList1 {
    public static void main(String[] args) {
        //创建一个集合,添加14个元素,这里我只是想测试大于默认10个元素大小的情况
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(1);
        list.add(2);
        list.add(1);
        list.add(2);
        list.add(1);
        list.add(2);
        list.add(1);
        list.add(2);
        list.add(1);
        list.add(2);
        list.add(1);
        list.add(2);
        //将这个14个元素的集合为构造参数,创建一个集合
        List<Integer> list1 = new ArrayList<>(list);
        list1.add(1);//此处打断点进入,查看size的值 14 和elementData的长度  14。这里不管前面是几多,一定会扩容。因为这样创建的list1对象的elementData长度再没有进行操作之前一定是和自己的size相等的
    }
}    

 

 Vector与ArrayList一样,也是通过数组实现的,不同的是它使用synchronized支持线程的同步,即某一时刻只有一个线程能够写Vector,避免多线程同时写而引起的不一致性,但实现同步需要很高的花费,因此,访问它比访问ArrayList慢。现在不常用。

替代方案:可以使用 Collections.synchronizedList(); 得到一个线程安全的 ArrayList。

 

    List<String> list = new ArrayList<>();
    List<String> synList = Collections.synchronizedList(list);

也可以使用 concurrent 并发包下的 CopyOnWriteArrayList 类。

另外Vector的子类Stack类代表后进先出堆栈的对象。 它扩展了类别Vector与五个操作,允许一个向量被视为堆栈。 设置在通常的push()(其实就是新增,只是多了封装返回新增对象的操作)和pop()(其实就是调用了下peek,获取栈顶的对象,移除并返回)操作,以及peek()(获取栈顶的对象),以测试堆栈是否为empty的方法,以及向search()在栈中距栈顶的距离。

LinkedList基于双向链表实现,使用 Node 存储链表节点信息。

使用 Node 存储链表节点信息。

LinkedList 提供了以下三个成员变量。size,first,last。

 transient int size = 0;
 transient Node<E> first;
 transient Node<E> last;

其中 size 为 LinkedList 的大小,first 和 last 分别为链表的头结点和尾节点。Node 为节点对象。Node 是 LInkedList 的内部类,定义了存储的数据元素,前一个节点和后一个节点,典型的双链表结构。

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;

    Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
    }
}

//to~do

ArrayList 基于动态数组实现,LinkedList 基于双向链表实现。ArrayList 和 LinkedList 的区别可以归结为数组和链表的区别:

数组支持随机访问,但插入删除的代价很高,需要移动大量元素;
链表不支持随机访问,但插入删除只需要改变指针

 posted on 2020-03-20 00:24  いつも何度でも  阅读(405)  评论(0编辑  收藏  举报