溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java封裝數(shù)組之動態(tài)數(shù)組實現(xiàn)方法詳解

發(fā)布時間:2020-08-27 07:00:06 來源:腳本之家 閱讀:199 作者:WFaceBoss 欄目:編程語言

本文實例講述了Java封裝數(shù)組之動態(tài)數(shù)組實現(xiàn)方法。分享給大家供大家參考,具體如下:

前言:在此之前,我們封裝的數(shù)組屬于靜態(tài)數(shù)組,也即數(shù)組空間固定長度,對于固定長度的數(shù)組當元素超過容量時會報數(shù)組空間不足。為了能更好的使用數(shù)組,我們來實現(xiàn)一個可以自動擴充容量的數(shù)組。

實現(xiàn)思路:

1.當數(shù)組容量達到事先定義值時創(chuàng)建一個空間是data數(shù)組兩倍的newData數(shù)組(擴容);

2.把data數(shù)組中的元素全部賦值到newData數(shù)組中;

3.把data數(shù)組重新執(zhí)行newData數(shù)組。

 一、定義核心擴容方法

// 數(shù)組擴容
private void resize(int newCapacity){
    E[] newData = (E[]) new Object[newCapacity];
    for (int i = 0; i < size; i++) {
        newData[i] = data[i];
    }
    data = newData;
}

二、改進之前的數(shù)組添加元素方法(數(shù)組空間不夠時自動擴容 --原理空間的2倍)

  //在第index個位置插入一個新元素
  public void add(int index, E e) {
    //(1)判斷當前需要插入值的位置是否合理,合理則轉(zhuǎn)入(3),否則拋出位置不合法異常
    if (index < 0 || index > size)
      throw new IllegalArgumentException("您選擇的位置不合法");

    //(2)先判斷當前數(shù)組容量是否已滿,滿則進行容量擴充
    if (size == data.length)
      resize(data.length * 2);


    //將index位置之后的元素往后依次移動一位
    for (int i = size - 1; i >= index; i--) {
      //(3)將index之后的元素依次往后移動一位,然后將新元素插入到index位置
      data[i + 1] = data[i];
    }
    data[index] = e;
    //(4)維護size值
    size++;
  }

三、改進之前的數(shù)組刪除元素方法(數(shù)組空間空閑太大就會縮容(原來空間的1/2))

//從數(shù)組中刪除index位置的元素,返回刪除的元素
  public E remove(int index) {
    //1.判斷索引的選擇是否合法
    if (index < 0 || index > size)
      throw new IllegalArgumentException("您選擇的位置不合法");

    //2.先存儲需要刪除的索引對應(yīng)的值
    E ret = data[index];

    //將索引為index之后(index)的元素依次向前移動
    for (int i = index + 1; i < size; i++) {
      //3.執(zhí)行刪除--實質(zhì)為索引為index之后(index)的元素依次向前移動,將元素覆蓋
      data[i - 1] = data[i];
    }
    //4.維護size變量
    size--;
    // loitering objects != memory leak 手動釋放內(nèi)存空間
    data[size] = null;
    if (size == data.length / 2) {
      resize(data.length / 2);
    }
    //5.返回被刪除的元素
    return ret;
  }

通過以上,我們就可以實現(xiàn)一個動態(tài)的數(shù)組。

測試一下改進后的代碼:

1.測試addLast()

 DynamicArray<Integer> arr=new DynamicArray<Integer>(10);
    for (int i = 0; i < 10; i++) {
      arr.addLast(i);
    }
    System.out.println("添加數(shù)組元素:");
    System.out.println(arr);

結(jié)果為:

Java封裝數(shù)組之動態(tài)數(shù)組實現(xiàn)方法詳解

2.測試add(int index,E e)方法

 arr.add(1, 100);
 System.out.println("在數(shù)組指定索引位置插入元素e:");
 System.out.println(arr);

 結(jié)果:

Java封裝數(shù)組之動態(tài)數(shù)組實現(xiàn)方法詳解

現(xiàn)在數(shù)組已經(jīng)從剛才定義的容量為10個變?yōu)榱巳萘繛?0個,數(shù)組中元素為11個,為此實現(xiàn)了數(shù)組擴容。

3.測試removeLast方法

 System.out.println("刪除數(shù)組最后一個元素:");
  arr.removeLast();
 System.out.println(arr);

結(jié)果為:

Java封裝數(shù)組之動態(tài)數(shù)組實現(xiàn)方法詳解

此時我們可以看出,刪除一個元素之后,數(shù)組容量又從新變?yōu)榱?0個。

本節(jié)所有代碼:

/**
 * 3.動態(tài)數(shù)組
 * 數(shù)組容量可變
 */


public class DynamicArray<E> {
  //使用private 的目的是防止用戶從外界修改,造成數(shù)據(jù)不一致
  private E[] data;
  private int size;//數(shù)組中元素個數(shù)

  //構(gòu)造函數(shù),傳入數(shù)組的容量capacity構(gòu)造Array函數(shù)
  public DynamicArray(int capacity) {
    data = (E[]) new Object[capacity];//泛型不能直接實例化
    size = 0;
  }

  //無參構(gòu)造函數(shù),默認數(shù)組的容量capacity=10
  public DynamicArray() {
    this(10);
  }

  //獲取數(shù)組中元素個數(shù)
  public int getSize() {
    return size;
  }

  //獲取數(shù)組的容量
  public int getCapacity() {
    return data.length;
  }

  //獲取數(shù)據(jù)是否為空
  public boolean iEmpty() {
    return size == 0;
  }

  //向所有元素后添加元素
  public void addLast(E e) {
    add(size, e);//size表示此時的最后一個元素
  }

  //在所有元素之前添加一個新元素
  public void addFirst(E e) {
    add(0, e);//0表示第一個位置
  }

  //在第index個位置插入一個新元素
  public void add(int index, E e) {
    //(1)判斷當前需要插入值的位置是否合理,合理則轉(zhuǎn)入(3),否則拋出位置不合法異常
    if (index < 0 || index > size)
      throw new IllegalArgumentException("您選擇的位置不合法");

    //(2)先判斷當前數(shù)組容量是否已滿,滿則進行容量擴充
    if (size == data.length)
      resize(data.length * 2);


    //將index位置之后的元素往后依次移動一位
    for (int i = size - 1; i >= index; i--) {
      //(3)將index之后的元素依次往后移動一位,然后將新元素插入到index位置
      data[i + 1] = data[i];
    }
    data[index] = e;
    //(4)維護size值
    size++;
  }

  //獲取index索引位置的元素
  public E get(int index) {
    //(1)判斷當前需要插入值的位置是否合理,合理則轉(zhuǎn)入(2),否則拋出位置不合法異常
    if (index < 0 || index > size)
      throw new IllegalArgumentException("您選擇的位置不合法");

    //(2)返回索引index對應(yīng)的值
    return data[index];
  }

  //獲取最后一個元素
  public E getLast() {
    return get(size - 1);
  }

  //獲取第一個元素
  public E getFirst() {
    return get(0);
  }

  //修改index索引位置的元素為e
  void set(int index, E e) {
    //(1)判斷當前需要插入值的位置是否合理,合理則轉(zhuǎn)入(2),否則拋出位置不合法異常
    if (index < 0 || index > size)
      throw new IllegalArgumentException("您選擇的位置不合法");

    //(2)修改索引index對應(yīng)的值
    data[index] = e;
  }

  //查找數(shù)組中是否包含元素e
  public boolean contains(E e) {
    for (int i = 0; i < size; i++) {
      if (data[i] == e)
        return true;
    }
    return false;
  }

  //查找數(shù)組中元素e所在的索引(只是一個),如果不存在元素e,則返回-1;
  public int find(E e) {
    for (int i = 0; i < size; i++) {
      if (data[i] == e)
        return i;
    }
    return -1;
  }

  //從數(shù)組中刪除index位置的元素,返回刪除的元素
  public E remove(int index) {
    //1.判斷索引的選擇是否合法
    if (index < 0 || index > size)
      throw new IllegalArgumentException("您選擇的位置不合法");

    //2.先存儲需要刪除的索引對應(yīng)的值
    E ret = data[index];

    //將索引為index之后(index)的元素依次向前移動
    for (int i = index + 1; i < size; i++) {
      //3.執(zhí)行刪除--實質(zhì)為索引為index之后(index)的元素依次向前移動,將元素覆蓋
      data[i - 1] = data[i];
    }
    //4.維護size變量
    size--;
    // loitering objects != memory leak 手動釋放內(nèi)存空間
    data[size] = null;

    //縮容操作
    if (size == data.length / 2 && data.length != 0) {
      resize(data.length / 4);
    }
    //5.返回被刪除的元素
    return ret;
  }

  //從數(shù)組中刪除第一個元素,返回刪除的元素
  public E removeFirst() {
    return remove(0);
  }

  //從數(shù)組中刪除最后一個元素,返回刪除的元素
  public E removeLast() {
    return remove(size - 1);
  }

  //從數(shù)組中刪除元素(只是刪除一個)
  public void removeElement(E e) {
    int index = find(e);
    if (index != -1)
      remove(index);
  }

  // 數(shù)組擴容方法
  private void resize(int newCapacity) {
    E[] newData = (E[]) new Object[newCapacity];
    for (int i = 0; i < size; i++) {
      newData[i] = data[i];
    }
    data = newData;
  }

  @Override
  public String toString() {
    StringBuilder res = new StringBuilder();
    res.append(String.format("Array:size=%d, capacity=%d\n", size, data.length));
    res.append('[');
    for (int i = 0; i < size; i++) {
      res.append(data[i]);
      if (i != size - 1) {
        res.append(",");
      }
    }
    res.append(']');
    return res.toString();
  }

}

測試代碼:

public class test {
  public static void main(String[] args) {

    DynamicArray<Integer> arr=new DynamicArray<Integer>(10);
    for (int i = 0; i < 10; i++) {

      arr.addLast(i);
    }
    System.out.println("添加數(shù)組元素:");
    System.out.println(arr);

    arr.add(1, 100);
    System.out.println("在數(shù)組指定索引位置插入元素e:");
    System.out.println(arr);

    System.out.println("刪除數(shù)組最后一個元素:");
    arr.removeLast();
    System.out.println(arr);

  }
}

更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)組操作技巧總結(jié)》、《Java字符與字符串操作技巧總結(jié)》、《Java數(shù)學(xué)運算技巧總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》及《Java操作DOM節(jié)點技巧總結(jié)》

希望本文所述對大家java程序設(shè)計有所幫助。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI