Java数据结构漫谈-ArrayList
ArrayList是一个基于数组实现的链表(List),这一点可以从源码中看出:
transient Object[] elementData; // non-private to simplify nested class access
可以看出ArrayList的内部是给予数组来处理的。
从ArrayList中查找一个元素的index,其时间复杂度是o(n),其源码如下所示:
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
ArrayList支持Clone,是使用Arrays.copyOf(Object[],int)来进行的:
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
ArrayList中根据index获取数组的时间复杂度是o(1),其源码如下:
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
public E get(int index) {//看这里
rangeCheck(index);
return elementData(index);
}
替换指定的位置的元素,时间复杂度也是o(1):
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
在末尾添加一个元素的时间复杂度也是o(1):
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
这里需要注意的是,其容量是可以扩展的,其可以扩展的最大容量是Integer.MAX_VALUE-8,由
int newCapacity = oldCapacity + (oldCapacity >> 1)
可以看出,每次是尝试扩容原来的1.5倍:
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_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 static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
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);
}
添加到指定index位置的时间复杂度是o(n),这里需要先把这个位置以及之后的元素统一向后移一位:
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
删除指定index位置的元素时间复杂度也是o(n),这里需要把这个元素之后的所有的元素向前移一位:
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = 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;
}
删除一个元素的时间复杂度也是o(n),显示查出来这个元素,删除,之后是把后面的元素向前进一位:
public 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;
}
private void fastRemove(int index) {
modCount++;
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
}
虽然在申明存储数组的时候,申明了不可被序列化,但是只要保存的对象是可序列化的,这个ArrayList还是可以序列化的:
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject(); // Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size); // Write out all elements in the proper order.
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
} if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
} private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff
s.defaultReadObject(); // Read in capacity
s.readInt(); // ignored if (size > 0) {
// be like clone(), allocate array based upon size not capacity
ensureCapacityInternal(size); Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
从以上的情况来看,ArrayList不是线程安全的,在进行index查找和最后插入的时候具有比较明显的时间复杂度优势。
但是,ArrayList的扩容操作,以及扩容产生的空间浪费一直是被人诟病的地方,另外在其中间进行插入的操作也不尽人意,时间复杂度是o(n)。
Java数据结构漫谈-ArrayList的更多相关文章
- Java数据结构漫谈-Stack
Stack(栈)是一种比较典型的数据结构,其元素满足后进先出(LIFO)的特点. Java中Stack的实现继承自Vector,所以其天然的具有了一些Vector的特点,所以栈也是线程安全的. cla ...
- Java数据结构漫谈-LinkedList
同样是List的数据结构,LinkedList是使用了前后指针,指明节点的方式来表示链表的,这与之前介绍的ArrayList http://www.cnblogs.com/yakovchang/p/j ...
- java数据结构之ArrayList
一.ArrayList源码注释 /** * ArrayList源码分析,jdk版本为1.8.0_121 */ public class ArrayList<E> extends Abstr ...
- Java 数据结构之ArrayList
ArrayList:数组队列,就是动态数组,可以动态的增加和减少元素.实现了ICollection和IList接口.灵活的设置数组的大小 具体的用法: 1.创建:ArrayList list = ne ...
- Java数据结构漫谈-Vector
List除了ArrayList和LinkedList之外,还有一个最常用的就是Vector. Vector在中文的翻译是矢量,向量,所以大家喜欢把Vector叫做矢量数组,或者向量数组. 其实就底层实 ...
- Java数据结构ArrayList
Java数据结构ArrayList /** * <html> * <body> * <P> Copyright JasonInternational</p&g ...
- Java数据结构之树和二叉树(2)
从这里始将要继续进行Java数据结构的相关讲解,Are you ready?Let's go~~ Java中的数据结构模型可以分为一下几部分: 1.线性结构 2.树形结构 3.图形或者网状结构 接下来 ...
- Java数据结构之树和二叉树
从这里开始将要进行Java数据结构的相关讲解,Are you ready?Let's go~~ Java中的数据结构模型可以分为一下几部分: 1.线性结构 2.树形结构 3.图形或者网状结构 接下来的 ...
- Java数据结构之线性表
从这里开始将要进行Java数据结构的相关讲解,Are you ready?Let's go~~ java中的数据结构模型可以分为一下几部分: 1.线性结构 2.树形结构 3.图形或者网状结构 接下来的 ...
随机推荐
- (转)ASP.NET版本的Kindeditor插件的使用(同步)
昨天老大让我自己下载一个kindeditor说要放到“描述”功能中,并且不能提交(一边在textarea中写一边在label控件中将数据显示出来),由于从来没弄过,实在费了一翻劲.所以将此记录下来,一 ...
- winform 获取当前项目所在的路径
代码: string curAppPath = System.IO.Directory.GetParent(System.Environment.CurrentDirectory).Parent.Fu ...
- MYSQL显示数据库内每个表拥有的触发器
一 所有数据库->所有触发器: SELECT * FROM information_schema.triggers; 二 当前数据库->当前所有触发器(假设当前数据库为gmvcs_ba ...
- js带箭头左右翻动控制
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- ArrayList 练习
ArrayList list = new ArrayList(); Random rd = new Random(); ; i <; i++) { , ); //是否包含当前数字 if (!li ...
- 关于R文件丢失的一个问题
android studio在编辑布局文件时,一般为了省事,如TextView控件中的text属性这样写 android:text="<500",编译不会报错,但是运行时会出 ...
- uva 10609 - Fractal
题目大意:给出A,B两个点的坐标,以及T,每次找到A.B的四等分点C,D,然后以AB/2为边长,C,D为顶点,构建一个等边三角形,E为另外一个顶点,然后再对C,E:E,D做同样的操作,直到构建的等边三 ...
- ubuntu 启用apache2 虚拟机配置
Ubuntu 启用apache2 虚拟机配置 http://jingyan.baidu.com/article/5d6edee20b78e999eadeecf7.html
- python学习第十天 -- 函数
稍微学过其他编程语言的人都应该了解函数的概念.在这里就不做过多的介绍. Python内置了很多有用的函数,我们可以也直接调用. 可以直接从Python的官方网站查看文档: http://docs.py ...
- 关于KMP算法理解(快速字符串匹配)
参考:http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html 2016-08- ...