1.定义
在计算机科学中,数组是由一组元素(值或变量)组成的数据结构,每个元素有至少一个索引或键来进行标识。
因为数组内的元素是连续存储的,所以数组中元素的地址,可以通过其索引计算出来,例如:

知道了数组的数据起始地址BaseAddress,就可以由公式BaseAddress+i*size计算出索引i元素的地址
i即索引,在Java,C等语言都是从0开始
size是每个元素占用字节,例如int占4,double占8
2.性能

3.随机访问
即根据索引查找元素,时间复杂度为O(1)
4.动态数组
package com.DyamicArray;
//动态数组
public class DynamicArray {
private int size = 0; //逻辑大小
private int capacity = 8; //容量
private int[] array = {};//建立一个空数组(懒惰初始化:刚开始不这么大,用到的时候再给你)
public void addLast(int element) {
// array[size] = element;
// size++;
add(size, element);
}
//插入元素
public void add(int index, int element) {//插入的位置和插入的值
checkAndGrow();
if (index >= 0 && index < size) {
//将数组中从指定索引位置开始的元素向后移动一位,为新元素的插入腾出空间。具体来说,它将array[index]到array[size-1]范围内的所有元素复制到array[index+1]到array[size]的位置上。
System.arraycopy(array, index, array, index + 1, size - index);
} else {
throw new RuntimeException("index out of bound");
}
array[index] = element;
size++;
}
private void checkAndGrow() {
//逻辑大小和容量比较(容量检查)
if (size == 0) {
array = new int[capacity];
}else if (size == capacity) {
//进行1.5倍扩容
capacity += capacity >> 1;
int[] newArray = new int[capacity];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
}
//删除元素
public void remove(int index) {
if (index < size - 1) {//
int removed = array[index];
//移动的数组,移动的起始位置,移动的数组,移动的起始位置,移动的数组长度
System.arraycopy(array, index + 1, array, index, size - index - 1);
size--;
} else {
throw new RuntimeException("index out of bound");
}
}
}

5.二维数组


1201

被折叠的 条评论
为什么被折叠?



