It features an array of
- Elements in the array are sequentially stored in the memory, logically sequential table
- Memory is one of memory units, each memory cell has its own address
- After initialization of the array, a fixed space
- Array indices start from 0
time complexity
- Array element read random access way: array [3], regardless of the size of the input array, and therefore the time complexity is O (1)
- Updating the array elements manner: array [3] = 10, regardless of the size of the input array, the time complexity of O (1);
- Array element is inserted, is inserted in the worst possible head array, the entire array must index after a shift, the time complexity of O (n)
- Delete elements of the array, the same principle of insertion elements, time complexity is O (n)
Number 组 demo
package com.cc.array;
public class MyArray {
private int [] array;
//数组的实际长度
private int size;
public MyArray(int capacity) {
array=new int[capacity];
size=0;
}
/**
* 数组插入元素
* @param index
* @param element
* @throws Exception
*/
public void insert(int index,int element) throws Exception{
if (index<0||index>size)
throw new IndexOutOfBoundsException("数组下标越界!");
//数组的实际长度大于数组容器的长度,对数组进行扩容
if (size>=array.length)
resize();
//从右向左至插入位置,每个元素向右移动一位
for (int i=size-1;i>=index;i--){
array[i+1]=array[i];
}
//插入位置的元素为当前插入的元素
array[index]=element;
//数组的实际长度加1
size++;
}
/**
* 实现数组的扩容
*/
public void resize(){
//新数组的容器的长度在原来数组容器的长度上*2,实现扩容
int [] newArray =new int[array.length*2];
//数组复制,原数组,原数组复制的起位置,目标数组,目标数组的起始位置,复制的长度
System.arraycopy(array,0,newArray,0,array.length);
//实现长度扩容
array=newArray;
}
/**
* 数组输出
*/
public void out(){
for (int i = 0; i <array.length; i++) {
System.out.println(array[i]);
}
}
/**
* 删除指定位置的元素
* @param index
* @return
*/
public int delete(int index){
if (index<0||index>=size)
throw new IndexOutOfBoundsException("数组下标越界!");
int deleteElement =array[index];
//将后一个元素赋值给钱面一个元素,防止数组越界,i<size-1,因此array[i+1]才不会越界
for(int i=index;i<size-1;i++){
array[i]=array[i+1];
}
//将最后一个元素改为初始值0
array[size-1]=0;
//数组的实际长度减一
size--;
return deleteElement;
}
public static void main(String[] args) throws Exception {
MyArray myArray =new MyArray(4);
myArray.insert(0,1);
myArray.insert(1,2);
myArray.insert(2,3);
myArray.insert(3,4);
myArray.insert(4,25);
// myArray.out();
myArray.delete(1);
myArray.out();
}
}