ArrayList解析
来源:互联网 发布:时时彩做计划软件 编辑:程序博客网 时间:2024/05/17 17:39
1.说明:
ArrayList内部实现是以数组实现,其最重要的一点就是能够自动扩容,也就是我们常常说的"动态数组",当超出其长度限制的时候会扩展为原来的1.5倍,如果扩展1.5倍还不满足需求,直接扩展为需求值,其默认容量为10。
2.源码解析:
(1)add函数
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
(2)put函数
public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
(3)get函数
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}
(4)remove函数
public E remove(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++;
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
(5)ensureCapacityInternal自动扩容机制
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 扩展为原来的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 如果扩展到原来的1.5倍还不满足需求,直接扩为需求值
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);
}
阅读全文
0 0
- ArrayList解析
- Arraylist解析
- ArrayList 解析
- ArrayList解析
- ArrayList 源码解析
- ArrayList源码解析
- android源码解析 -- ArrayList
- ArrayList源码解析
- ArrayList源码解析
- 深入解析ArrayList
- ArrayList,hashSet解析
- ArrayList源码解析
- ArrayList源码解析
- ArrayList LinkedList源码解析
- ArrayList 源码解析
- ArrayList集合源码解析
- ArrayList源码解析
- ArrayList类源码解析
- python学习—Day16—类(一般形式、继承)
- 一整数数组,将奇数放在前面,偶数放在后面
- 红黑树
- 斐波那契?
- uva10608
- ArrayList解析
- Python FTP
- DecimalFormat
- Android RxJava 实战讲解:优雅实现 网络请求轮询
- 引用类型与垃圾回收
- springmvc log4j设置日志输出级别
- NYOJ 364 HDU 1052 田忌赛马
- (10)global-results、继承包
- 虚拟机的几种网络连接方式