超级数组,list底层实现模仿

来源:互联网 发布:程颢 知乎 编辑:程序博客网 时间:2024/05/09 12:31


public class SuperArray { // 定义属性 private int[] array = new int[20]; //数组中已经存放的元素 private int size; // 定义行为 // 增加 public void add(int values) {  if (this.size < this.array.length) {   this.array[this.size] = values;   this.size++;  } else {   int[] newArray = new int[this.array.length + 10];   System.arraycopy(array, 0, newArray, 0, this.array.length);   this.array = newArray;   this.add(values);  } } // 删除 public void delete(int index) {  if (index < this.size && index >= 0) {   for (int i = index; i < this.size - 1; i++) {    this.array[i] = this.array[i + 1];   }   this.size--;  }  if (this.array.length > 20 && (this.array.length - this.size) > 10) {   int[] newArray = new int[this.array.length - 10];   System.arraycopy(array, 0, newArray, 0, this.array.length - 10);   this.array = newArray;  } } // 查询 public int get(int index) {  if (index >= 0 && index < this.size) {   return this.array[index];  }  throw new ArrayIndexOutOfBoundsException(); } // 修改 public void set(int index, int values) {  if (index >= 0 && index < this.size) {   this.array[index] = values;  } } // 输出元素个数 public int size() {  return this.size; }}


0 0
原创粉丝点击