数据结构
数据结构:
数据之间存在的一个或者多种的特定的关系元素的集合!
分类
根据数据对象的数据元素之间的关系,分类为逻辑结构与物理结构
逻辑结构:
1.集合结构
2.线性结构
3.树形结构
4.图形结构
物理结构:
1.顺序存储结构:
内存地址是连续的,比如:ArrayList
2.链式存储结构
内存地址不连续,可以找到下一个节点,形成链,比如:LinkedList
顺序存储ArrayList
简单看一下ArrayList的源码,里面维护了一个Object的数组,每次增加或者删除元素都要移动后面的元素!
/**
* Default initial capacity. 默认数组的长度,java与Android可能会有差别
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
// 维护一个数组
transient Object[] elementData;
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
下面看几个主要用到的函数,增删改查:
public boolean add(E e) {
// 检查容量,适当扩容
ensureCapacityInternal(size + 1); // Increments modCount!!
// 给数组元素赋值
elementData[size++] = e;
return true;
}
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);
//置空元素,让GC回收
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
// 返回指定位置的元素
return (E) elementData[index];
}
大概就看到这里了!ArrayList的源码比较简单,就是操作一个成员数组!