ArrayList分析
来源:互联网 发布:人脸识别算法代码 编辑:程序博客网 时间:2024/05/16 00:25
我们经常使用的集合,但需要去了解一下其中的源码
集合是用来存储信息,那么这里进行如下分析
1.使用什么方式存储
2.如何完成扩容的,扩容的机制是什么?
3.核心方法
4.其他方法
那么我们来看源码,首先将源码通读一遍后,可以发现,arrayList中将数据存放在一个数组中
transient Object[] elementData;
那么以后对其的增加和删除元素都是对数组的操作。
接下来它是如何完成扩容的,在平常的使用中,都不会去关注集合的容量,以为它是无限大的,然后并不是。首先对数组有一个认识后,那么对集合的初始化时,就对数组进行了初始化,要么为空,要么给定一个长度
//这个就是空的数组public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } private static final Object[] EMPTY_ELEMENTDATA = {};
//给定一个初始的容量public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } }
还有一种就是
public ArrayList(c)该构造函数直接放一个集合放入到ArrayList中,这样集合的初始容量就为c的长度。
它的扩容机制是什么呢?
那么我们在使用add,remove的时候,是如何扩容的,
跳入到add方法中
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
ensureCapacityInternal(size + 1);就是在扩容,将数组长度增加1,如果当数组为空,同时又调用了addAll(c)方法,那么数组将增加c的长度。(参看源码)
当移除时数组的长度-1,同时为了将对象的引用清空,调用了elementData[–size] = null;方法。
那么arrayList的扩容机制就是需要的时候增加或者减少数组的大小。
接下来看其中的核心的源码
经常使用到的就是get,add,remove,遍历Iterator
回忆一下我们是如何从数组中去的数据的,data[i],这样就从数组中就去得了数据,如何进行遍历了,for循环,如何删除一条数据的,data[i] = null,不过这里讲数组中的数据删除后,为了减少存储空间的碎片,调用了System.arraycopy(elementData, index+1, elementData, index, numMoved);这是将前部分和后部分进行拼接。如何添加的呢,先扩容,然后调用elementData[size++] = e;方法增加元素e。
现在有一点明白ArrayList,不过是对数组的操作进行了封装。
这里贴上其中的核心方法
//获取元素public E get(int index) { rangeCheck(index);//检测index是否超过了数组的长度 return elementData(index);//调用elementData(index)方法}E elementData(int index) { return (E) elementData[index];//从数组中取出元素}
//添加元素public boolean add(E e) { ensureCapacityInternal(size + 1); //进行扩容 elementData[size++] = e;//数组尾端添加元素e return true; }//在index位置上添加元素public void add(int index, E element) { rangeCheckForAdd(index);//检测index是否超过了数组的长度 ensureCapacityInternal(size + 1); // 扩容 System.arraycopy(elementData, index, elementData, index + 1,size - index);//思路:将元素重新移动到一个数组中,数组index空出来 elementData[index] = element;//数组index赋值 size++;//数组长度增加 }
//删除元素public E remove(int index) { rangeCheck(index);//检测index是否超过了数组的长度 modCount++; E oldValue = elementData(index);//获取index位置上的元素 int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved);//将index前端和index的后端拼接起来,数组最后端清空,数组长度-1 elementData[--size] = null; // clear to let GC do its work return oldValue; }//移除元素o,arrayList集合元素存储的值允许为null,遍历查询等于元素o的值,移除,返回truepublic boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; }
接下来出了使用for循环遍历arrayList,还可以使用迭代器。首先来看看我们如何使用遍历。
Iterator iter = l.iterator(); while(iter.hasNext()){ String str = (String) iter.next(); System.out.println(str);
这里使用while进行遍历,判断条件hashNext()是否为真,next()方法获取值。接下啦看看其中的源码:
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(); } } @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
其中使用变量cursor,每次调用next()方法,cursor++,这个使用能够理解,上面while遍历和for循环一样,cursor相当于游标,cursor指向第一个值,每次调用next()方法,获取当前值,cursor移动到下一个元素。直到cursor==Size时while循环终止。下面还有一个方法
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(); } } }
它继承了Itr实现了Iterator,可以进行双向迭代,这里从后向前遍历时,cursor-1。
那么迭代就是控制一个游标cursor,调用next(),previous()方法时,cursor++,cursor–。
ArrayList分析其中的源码后,应该有一下收获:
1.ArrayList集合其中使用数组存储。其中就是对数组的操作。
2.扩容机制,每次添加或删除操作后,容量就增加或减少1,而使用addAll(c)时,增加c.size()的长度。
3.迭代器,迭代器使用cursor游标,每次调用next方法,cursor移动到下一个元素。
- ArrayList分析
- ArrayList分析
- ArrayList分析
- ArrayList分析
- ArrayList分析
- ArrayList分析
- ArrayList分析
- ArrayList分析
- ArrayList源码分析
- ArrayList的用法分析
- ArrayList源码分析
- ArrayList 源码分析
- ArrayList源码分析
- ArrayList源代码分析
- ArrayList LinkedList 源码分析
- ArrayList,LinkedList源码分析
- 源码分析之ArrayList
- ArrayList 源码分析
- 13.总线设备驱动模型(1)-总线设备驱动模型
- PHP JSON
- MySQL学习(三)
- c++ operatot重载
- AJAX 教程
- ArrayList分析
- AJAX 简介
- AJAX 实例
- AJAX - 创建 XMLHttpRequest 对象
- AJAX - 向服务器发送请求请求
- Android 消息机制
- AJAX - 服务器 响应
- how to change file names in matlab
- AJAX - onreadystatechange 事件