Inserción y eliminación de matriz java

public class ArrayList {
    
    

  // 此处需要声明一个数组,作为底层存储
  int[] array = new int[20];
  int size = 0;

  public ArrayList() {
    
    
  }

  // 获取数组的长度
  public int size() {
    
    
    return this.size;
  }

  // 数组获取某个索引值
  public int get(int index) {
    
    
    return this.array[index];
  }

  // 添加元素在末尾 
  public void add(int element) {
    
    
    //相当于调用传入this.size
    this.add(this.size, element);
  }

  // 添加元素在中间
  public void add(int index, int element) {
    
    
    if (index < 0 || index > this.size) {
    
    
      return;
    }

    // 支持扩容
    // TODO
    this.judgeMemory(this.size + 1);

    // 元素依次右移
    for (int i = this.size - 1; i >= index; i--) {
    
    
      this.array[i + 1] = this.array[i];
    }
    // 插入元素
    this.array[index] = element;
    // 调整size
    this.size++;
  }
  //扩容
  public void judgeMemory(int size){
    
    
    if(size > this.array.length){
    
    
      int[] newArray = new int[this.array.length*2];
      for(int i = 0; i < this.size; i++){
    
    
        newArray[i] = this.array[i];
      }
      this.array = newArray;
    }
  }

  // 删除元素
  public void remove(int index) {
    
    
    if (index < 0 || index > this.size - 1) {
    
    
      return;
    }

    // 元素依次左移
    for (int i = index; i < this.size - 1; i++) {
    
    
      this.array[i] = this.array[i + 1];
    }
    // 删除最后一个元素
    this.array[this.size - 1] = 0;
    // 调整size
    this.size--;
  }

  public static void main(String[] args) {
    
    
    ArrayList arrayList = new ArrayList();
    arrayList.add(1);
    arrayList.add(2);
    arrayList.add(3);
    arrayList.add(4);

    arrayList.add(0, 5);

    arrayList.remove(3);
  }
}

Supongo que te gusta

Origin blog.csdn.net/qq_37344867/article/details/122198652
Recomendado
Clasificación