数据结构之动态数组--接上篇
作者:互联网
//重置数组大小长度 private void resize(int newCapacity){ E[] newData = (E[]) new Object[newCapacity]; for(int i = 0 ; i < size ; i ++) newData[i] = data[i]; data = newData; }
main方法
package com.practice; import com.practice.Array.Array; public class Main { public static void main(String[] args) { // write your code here Array<Integer> arr = new Array<Integer>(); for(int i = 0 ; i < 10 ; i ++) arr.addLast(i); System.out.println(arr); arr.add(1,100); System.out.println(arr); arr.addFirst(-1); System.out.println(arr); /*arr.remove(2); System.out.println(arr); arr.removeElement(4); System.out.println(arr); arr.removeFirst(); System.out.println(arr);*/ } }
运行main方法测试
Array:size= 10 , capacity = 10 [0,1,2,3,4,5,6,7,8,9] Array:size= 11 , capacity = 20 [0,100,1,2,3,4,5,6,7,8,9] Array:size= 12 , capacity = 20 [-1,0,100,1,2,3,4,5,6,7,8,9]
元素个数小于当前数组容积
//从数组中删除index位置的元素,返回删除的元素 public E remove(int index){ if(index < 0 || index >= size ) throw new IllegalArgumentException("Set failed.Index is illegal."); E ret = data[index]; for(int i = index + 1 ; i < size ; i ++){ data[i-1] = data[i]; } size --; data[size] = null;//loitering objects != memory leak //如果当前元素个数小于当前数组容积的一般 if(size == data.length / 2) resize(data.length / 2); return ret; }
main方法
package com.practice; import com.practice.Array.Array; public class Main { public static void main(String[] args) { // write your code here Array<Integer> arr = new Array<Integer>(); for(int i = 0 ; i < 10 ; i ++) arr.addLast(i); System.out.println(arr); arr.add(1,100); System.out.println(arr); arr.addFirst(-1); System.out.println(arr); arr.remove(2); System.out.println(arr); arr.removeElement(4); System.out.println(arr); arr.removeFirst(); System.out.println(arr); } }
main方法运行结果
Array:size= 10 , capacity = 10 [0,1,2,3,4,5,6,7,8,9] Array:size= 11 , capacity = 20 [0,100,1,2,3,4,5,6,7,8,9] Array:size= 12 , capacity = 20 [-1,0,100,1,2,3,4,5,6,7,8,9] Array:size= 11 , capacity = 20 [-1,0,1,2,3,4,5,6,7,8,9] Array:size= 10 , capacity = 10 [-1,0,1,2,3,5,6,7,8,9] Array:size= 9 , capacity = 10 [0,1,2,3,5,6,7,8,9]
标签:arr,接上,--,System,println,Array,数据结构,out,size 来源: https://www.cnblogs.com/oneJavaWorkerStudy/p/16445971.html