动态扩容数组原理及实现
什么是数据结构?
数据结构是计算机存储、组织数据的方式;
线性表
线性表是具有 n 个相同类型元素的有限序列( n ≥ 0 )
- a1 是首节点(首元素), an 是尾结点(尾元素)
- a1 是 a2 的前驱, a2 是 a1 的后继
常见的线性表有:
数组
数组是一种顺序存储的线性表,所有元素的内存地址是连续的
在很多编程语言中,数组都有个致命的缺点: 无法动态修改容量
实际开发中,我们更希望数组的容量是可以动态改变的
动态数组(Dynamic Array)
动态数组接口设计
动态数组的结构:
- size
- elements
Java 中,成员变量会自动初始化,比如:
- int 类型自动初始化为 0
- 对象类型自动初始化为 null
清除所有元素 - clear()
核心代码是 size = 0,实际上不需要执行 elements = null ,size = 0 的操作已经对用户来说保证了无法访问动态数组中的元素了。
添加元素 - add(E element)、add(int index, E element)
add(E element):默认往数组最后添加元素;
add(int index, E element):在 index 位置插入一个元素;
比如要往 index = 2 的地方添加元素:
正确的顺序应当是:从后往前开始将 index = 2 以后的元素依次后移,然后赋值:
如果从前往后开始移动元素,会造成如下错误的后果:
代码实现:
public void add(int index, E element){
rangeCheckForAdd(index);
ensureCapacity(size + 1);
for (int i = size - 1; i > index; i--) {
elements[i + 1] = elements[i];
}
elements[index] = element;
size++;
}
public void add(E element){
add(size, element);
}
删除元素 - remove(int index)、清空数组 - clear()
例如,删除 index = 3 的数组元素,应当从前往后开始移动,用后面的元素覆盖前面的元素。
思考:最后一个元素如何处理?
如果存放 int 类型,size-- 后,最后一个元素已经无法访问了。 如果使用泛型,数组要注意内存管理(将元素置为null)。 使用泛型技术可以让动态数组更加通用,可以存放任何数据类型:
代码实现:
public E remove(int index){
rangeCheck(index);
E old = elements[index];
for (int i = index; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
elements[--size] = null;
return old;
}
public void clear(){
for (int i = 0; i < size; i++) {
elements[i] = null;
}
size = 0;
}
是否包含某个元素 - contains(E element)
关于 null 的处理主要看你的业务需求:是否可以存储 null 数据?
public boolean contains(E element){
return indexOf(element) != ELEMENT_NOT_FOUND;
}
public int indexOf(E element){
if(element == null){
for (int i = 0; i < size; i++) {
if(elements[i] == null) return i;
}
}else{
for (int i = 0; i < size; i++) {
if(elements[i].equals(element)) return i;
}
}
return ELEMENT_NOT_FOUND;
}
扩容 - ensureCapacity(int capacity)
相信看过视频的小伙伴一看这图就懂了。 扩容操作代码实现:
private void ensureCapacity(int capacity){
int oldCapacity = elements.length;
if (oldCapacity >= capacity) return;
int newCapacity = oldCapacity + (oldCapacity >> 1);
E[] newElements = (E[])new Object[newCapacity];
for (int i = 0; i < size; i++) {
newElements[i] = elements[i];
}
elements = newElements;
System.out.println("size="+oldCapacity+", 扩容到了"+newCapacity);
}
打印数组(toString)
- 重写
toString 方法 - 在
toString 方法中将元素拼接成字符串 - 字符串拼接建议使用
StringBuilder
@Override
public String toString() {
StringBuilder string = new StringBuilder();
string.append("size=").append(size).append(", [");
for (int i = 0; i < size; i++) {
if(0 != i) string.append(", ");
string.append(elements[i]);
}
string.append("]");
return string.toString();
}
泛型
使用泛型技术可以让动态数组更加通用,可以存放任何数据类型
public class ArrayList<E> {
private int size;
private E[] elements;
}
elements = (E[]) new Object[capacity];
对象数组 - Object[]
Object[] objects = new Object[7];
由于 Object 可以存放任何类型,因此无法固定 Object 占多少内存空间(根据传入不同的自定义对象,占用的空间都不同),因此实际上 Object 数组中存放的是对象的地址。 想要销毁对象,只需要将指向该对象的地址赋值为 null,没有地址引用该对象,则会自动被垃圾回收
内存管理细节:
清空数组clear()删除元素clear()
public void clear() {
for (int i = 0; i < size; i++) {
elements[i] = null;
}
size = 0;
}
public E remove(int index) {
rangeCheck(index);
E oldElement = elements[index];
for (int i = index; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
elements[--size] = null;
return oldElement;
}
int型动态数组源码(Java)
public class ArrayList {
private int size;
private int[] elements;
private static final int DEFAULT_CAPACITY = 10;
private static final int ELEMENT_NOT_FOUND = -1;
public ArrayList(int capacity) {
capacity = (capacity < DEFAULT_CAPACITY) ? DEFAULT_CAPACITY : capacity;
elements = new int[capacity];
}
public ArrayList(){
this(DEFAULT_CAPACITY);
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public boolean contains(int element){
return indexOf(element) != ELEMENT_NOT_FOUND;
}
public void add(int index, int element){
rangeCheckForAdd(index);
ensureCapacity(size + 1);
for (int i = size - 1; i > index; i--) {
elements[i + 1] = elements[i];
}
elements[index] = element;
size++;
}
public void add(int element){
add(size, element);
}
public int get(int index){
rangeCheck(index);
return elements[index];
}
public int set(int index, int element){
rangeCheck(index);
int old = elements[index];
elements[index] = element;
return old;
}
public int remove(int index){
rangeCheck(index);
int old = elements[index];
for (int i = index; i < size-1; i++) {
elements[i] = elements[i + 1];
}
size--;
return old;
}
public int indexOf(int element){
for (int i = 0; i < size; i++) {
if(elements[i] == element) return i;
}
return ELEMENT_NOT_FOUND;
}
public void clear(){
size = 0;
}
private void ensureCapacity(int capacity){
int oldCapacity = elements.length;
if(oldCapacity >= capacity) return;
int newCapacity = oldCapacity + (oldCapacity >> 1);
int[] newElements = new int[newCapacity];
for (int i = 0; i < size; i++) {
newElements[i] = elements[i];
}
elements = newElements;
System.out.println("size="+oldCapacity+", 扩容到了"+newCapacity);
}
private void outOfBounds(int index) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + size);
}
private void rangeCheck(int index){
if(index < 0 || index >= size){
outOfBounds(index);
}
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > size) {
outOfBounds(index);
}
}
@Override
public String toString() {
StringBuilder string = new StringBuilder();
string.append("size=").append(size).append(", [");
for (int i = 0; i < size; i++) {
if(0 != i) string.append(", ");
string.append(elements[i]);
}
string.append("]");
return string.toString();
}
}
泛型动态数组源码(Java)
@SuppressWarnings("unchecked")
public class ArrayList<E> {
private int size;
private E[] elements;
private static final int DEFAULT_CAPACITY = 10;
private static final int ELEMENT_NOT_FOUND = -1;
public ArrayList(int capacity) {
capacity = (capacity < DEFAULT_CAPACITY) ? DEFAULT_CAPACITY : capacity;
elements = (E[])new Object[capacity];
}
public ArrayList(){
this(DEFAULT_CAPACITY);
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public boolean contains(E element){
return indexOf(element) != ELEMENT_NOT_FOUND;
}
public void add(int index, E element){
rangeCheckForAdd(index);
ensureCapacity(size + 1);
for (int i = size - 1; i > index; i--) {
elements[i + 1] = elements[i];
}
elements[index] = element;
size++;
}
public void add(E element){
add(size, element);
}
public E get(int index){
rangeCheck(index);
return elements[index];
}
public E set(int index, E element){
rangeCheck(index);
E old = elements[index];
elements[index] = element;
return old;
}
public E remove(int index){
rangeCheck(index);
E old = elements[index];
for (int i = index; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
elements[--size] = null;
return old;
}
public int indexOf(E element){
if(element == null){
for (int i = 0; i < size; i++) {
if(elements[i] == null) return i;
}
}else{
for (int i = 0; i < size; i++) {
if(elements[i].equals(element)) return i;
}
}
return ELEMENT_NOT_FOUND;
}
public void clear(){
for (int i = 0; i < size; i++) {
elements[i] = null;
}
size = 0;
}
private void ensureCapacity(int capacity){
int oldCapacity = elements.length;
if(oldCapacity >= capacity) return;
int newCapacity = oldCapacity + (oldCapacity >> 1);
E[] newElements = (E[])new Object[newCapacity];
for (int i = 0; i < size; i++) {
newElements[i] = elements[i];
}
elements = newElements;
System.out.println("size="+oldCapacity+", 扩容到了"+newCapacity);
}
private void outOfBounds(int index) {
throw new IndexOutOfBoundsException("Index:" + index + ", Size:" + size);
}
private void rangeCheck(int index){
if(index < 0 || index >= size){
outOfBounds(index);
}
}
private void rangeCheckForAdd(int index) {
if (index < 0 || index > size) {
outOfBounds(index);
}
}
@Override
public String toString() {
StringBuilder string = new StringBuilder();
string.append("size=").append(size).append(", [");
for (int i = 0; i < size; i++) {
if(0 != i) string.append(", ");
string.append(elements[i]);
}
string.append("]");
return string.toString();
}
}
测试运行:
public static void main(String[] args) {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person(10, "jack"));
list.add(new Person(20, "rose"));
list.add(null);
list.add(null);
System.out.println("add()添加元素: " + list);
System.out.println("get()获取元素: " + list.get(0));
list.set(0, new Person(99, "ghost"));
System.out.println("set()设置元素值: " + list);
list.remove(0);
System.out.println("remove()删除元素: " + list);
list.clear();
System.out.println("clear()清空数组: " + list);
}
add()添加元素: size=4, [Person [age=10, name=jack], Person [age=20, name=rose], null, null]
get()获取元素: Person [age=10, name=jack]
set()设置元素值: size=4, [Person [age=99, name=ghost], Person [age=20, name=rose], null, null]
remove()删除元素: size=3, [Person [age=20, name=rose], null, null]
clear()清空数组: size=0, []
泛型动态数组源码(C++)
#include<iostream>
using namespace std;
#define ELEMENT_NOT_FOUND -1;
template<typename E>
class Array
{
private:
int m_size; // 元素数量
int m_capacity; // 数组容量
E * m_elements; // 指向首地址
void outOfBounds(int index) {
throw index;
}
void rangeCheck(int index); // 检查下标(get,set)
void rangeCheckForAdd(int index); // 检查下标(add)
void ensureCapacity(int capacity); // 检查容量及扩容
public:
Array(int capacity = 10);
~Array();
int size(); // 元素的数量
bool isEmpty(); // 是否为空
int indexOf(E element); // 查看元素的位置
bool contains(E element); // 是否包含某个元素
E set(int index, E element); // 设置index位置的元素
E get(int index); // 返回index位置对应的元素
void add(int index, E element); // 往index位置添加元素
void add(E element); // 添加元素到最后面
E remove(int index); // 删除index位置对应的元素
void clear(); // 清除所有元素
};
template<typename E>
void Array<E>::rangeCheck(int index) {
if (index < 0 || index >= m_size)
outOfBounds(index);
}
template<typename E>
void Array<E>::rangeCheckForAdd(int index) {
if(index < 0 || index > m_size)
outOfBounds(index);
}
template<typename E>
void Array<E>::ensureCapacity(int capacity) {
int oldCapacity = m_capacity;
if (oldCapacity >= capacity) return;
// 新容量为旧容量的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
E *newElements = new E[newCapacity];
for (int i = 0; i < m_size; i++) {
newElements[i] = m_elements[i];
}
delete[] m_elements; // 释放原空间
m_elements = newElements;
m_capacity = newCapacity;
cout << oldCapacity << "扩容为" << newCapacity << endl;
}
template<typename E>
Array<E>::Array(int capacity) {
m_capacity = (capacity < 10) ? 10 : capacity;
m_elements = new E[m_capacity];
}
template<typename E>
Array<E>::~Array() {
delete[] m_elements;
}
template<typename E>
int Array<E>::size(){
return m_size;
}
template<typename T>
bool Array<T>::isEmpty() {
return m_size == 0;
}
template<typename E>
int Array<E>::indexOf(E element) {
for (int i = 0; i < m_size; i++) {
if (m_elements[i] == element) return i;
}
return ELEMENT_NOT_FOUND;
}
template<typename E>
bool Array<E>::contains(E element) {
return indexOf(element) != ELEMENT_NOT_FOUND;
}
template<typename E>
E Array<E>::set(int index, E element) {
rangeCheck(index);
E old = element;
m_elements[index] = element;
return old;
}
template<typename E>
E Array<E>::get(int index) {
rangeCheck(index);
return m_elements[index];
}
template<typename E>
void Array<E>::add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacity(m_size + 1);
// 0 1 2 3 4 5
// 1 2 3 5 6 7
// index=3, element=4
for (int i = m_size; i > index; i--) {
m_elements[i] = m_elements[i-1];
}
m_elements[index] = element;
m_size++;
}
template<typename E>
void Array<E>::add(E element) {
add(m_size, element);
}
template<typename E>
E Array<E>::remove(int index) {
rangeCheck(index);
E old = m_elements[index];
// 0 1 2 3 4 5
// 1 2 3 5 6 7
// index=2
for (int i = index; i < m_size; i++) {
m_elements[i] = m_elements[i + 1];
}
m_elements[--m_size] = NULL;
return old;
}
template<typename E>
void Array<E>::clear() {
// m_elements = nullptr; // 不可行,直接清除了整个指针指向的地址
for (int i = 0; i < m_size; i++) {
m_elements[i] = NULL;
}
m_size = 0;
}
int main() {
Array<int> array;
for (int i = 0; i < 30; i++) {
array.add(i);
}
cout << "array.set(0, 99): " << array.set(0, 99) << endl;
cout << "array.remove(0): " << array.remove(0) << endl;
cout << "array.isEmpty(): " << array.isEmpty()<< endl;
cout << "array.cotains(5): " << array.contains(5) << endl;
cout << "size = " << array.size() << endl;
array.add(10, 99);
cout << "array.add(10, 99), size = " << array.size() << endl;
for (int i = 0; i < array.size() ; i++) {
if (i != 0) {
cout << ", ";
}
cout << array.get(i);
}
}
10扩容为15
15扩容为22
22扩容为33
array.set(0, 99): 99
array.remove(0): 99
array.isEmpty(): 0
array.cotains(5): 1
size = 29
array.add(10, 99), size = 30
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 99, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
|