//扩容与缩容publicvoidresize(int newCapacity){
T[] newData =(T[])newObject[newCapacity];for(int i =0; i < size; i++){
newData[i]= data[i];}
data = newData;}
4.向数组中添加元素
判断数组是否为空
我们的添加元素的位置不能大于数组长度
判断数组是否满了没满则调用上述的扩容为其扩容2倍,一般是扩容1.5倍
在尾部添加时直接添加
时间复杂度为O(1)
在头部添加时,需要把元素后移,然后再添加再第一个
所以数组添加慢 时间复杂度为O(n)
在中间添加时,如上,
时间复杂度为O(n/2)
综上来看 添加的时间复杂度为O(n)
//向数组中的末尾添加元素 size为我们始终添加元素的位置publicvoidaddTail(T ele)throws IllegalAccessException {add(ele, size);}//向数组指定位置添加元素publicvoidadd(T ele,int index)throws IllegalAccessException {//添加位置不能小于0也不能大于数组长度if(index <0|| index > size){thrownewIllegalAccessException("array is error!");}//判断数组是否已满,满就进行扩容if(size == data.length){resize(2* data.length);}//元素后移,从最后一个开始移动for(int i = size -1; i > index; i--){
data[i +1]= data[i];}
data[index]= ele;
size++;}//向数组的头部添加元素publicvoidaddHead(T ele)throws IllegalAccessException {add(ele,0);}
5.查询数组中的元素
判断数组是否为空
引进了索引,正是因为索引的存在,所以数组的特点就出来了,查询快
时间复杂度为O(1)
//获取头部元素public T getHeed()throws IllegalAccessException {returngetEleByIndex(0);}//获取指定位置元素public T getEleByIndex(int index)throws IllegalAccessException {if(index <0|| index > size -1){thrownewIllegalAccessException("array is error!");}return data[index];}//获取尾部元素public T getTail()throws IllegalAccessException {returngetEleByIndex(size -1);}
6.修改指定位置元素
判断数组是否为空
修改同查询一样借用索引十分迅速
时间复杂度为O(1)
//修改指定位置元素publicvoidsetEleByIndex(int index, T ele)throws IllegalAccessException {if(index <0|| index > size -1){thrownewIllegalAccessException("array is error!");}
data[index]= ele;}
7.移除指定位置的元素
判断数组是否为空
数组如果长度太长,使用元素太少容易造成空间浪费,引进了缩容
可以用现数组有3/4的容量被浪费时,可以考虑数组缩容
可以调用上述扩容同样方法,缩容其的1/2
在尾部删除时直接删除
时间复杂度为O(1)
在头部删除时,需要把元素前移,然后再长度减一,直接释放
所以数组删除慢 时间复杂度为O(n)
在中间删除时,如上,
时间复杂度为O(n/2)
综上来看 删除的时间复杂度为O(n)
//移除指定位置的元素public T removeEle(int index)throws IllegalAccessException {if(index <0|| index > size -1){thrownewIllegalAccessException("array is error!");}
T result = data[index];for(int i = index; i < size -1; i++){
data[i]= data[i +1];}
size--;//缩容if(size <= data.length /4&& data.length /2!=0){resize(data.length /2);}return result;}
8.根据元素判断数组中是否存在
只需要遍历一遍,有则返回索引
时间复杂度为O(1)
//找到指定元素的索引publicintgetIndex(T ele){int index =-1;for(int i =0; i < size; i++){if(data[i]== ele){
index = i;break;}}return index;}//判断数组中是否包含指定的元素publicbooleancontains(T ele){returngetIndex(ele)!=-1;}
9.重新toString
重写toString,这样可以快速输出数组,也是用数组的遍历来进行输出
@Overridepublic String toString(){
StringBuffer sb =newStringBuffer("[");for(int i =0; i < size; i++){
sb.append(data[i]);if(i != size -1){
sb.append(",");}}
sb.append("],数组的容量为:");
sb.append(data.length).append(",实际存放元素的个数:").append(size);return sb.toString();}