最近想寫點數據結構方面的東西,這不首篇介紹下最基礎的數據結構數組的一些知識點!
首先,數組的特點 適合查詢,但是刪除和修改有點慢!
話不多說,先看看手動實現的數組類Array吧! talk is poor , show me the codeing!
package com.hl.array; /** * Created by 帥氣的黑天鵝丶 on 2018/7/30. */ public class Array<E> { private E[] data; private int size; // 構造函數,傳入數組的容量capacity構造Array public Array(int capacity){ data = (E[])new Object[capacity]; size =0; } // 無參數的構造函數,默認數組的容量capacity=10 public Array(){ this(10); } // 獲取數組的容量 public int getCapacity(){ return data.length; } // 獲取數組中的元素個數 public int getSize(){ return size; } // 返回數組是否為空 public boolean isEmpty(){ return size == 0; } // 在index索引的位置插入一個新元素e public void add(int index,E e){ /*if (size==data.length) throw new IllegalArgumentException("add is failed,array is full");*/ if (index<0 || index>size) throw new IllegalArgumentException("Add failed. Require index >= 0 and index <= size."); if (size==data.length) resize(2*data.length); for (int i=size-1;i>=index;i--){ data[i+1] = data[i]; } data[index]=e; size++; } // 向所有元素后添加一個新元素 public void addLast(E e){ add(size,e); } // 在所有元素前添加一個新元素 public void addFirst(E e){ add(0,e); } // 獲取index索引位置的元素 public E get(int index){ if(index < 0 || index >= size) throw new IllegalArgumentException("Get failed. Index is illegal."); return data[index]; } // 修改index索引位置的元素為e public void set(int index,E e){ if(index < 0 || index >= size) throw new IllegalArgumentException("Get failed. Index is illegal."); data[index] = e; } // 查找數組中是否有元素e public boolean contains(E e){ for (int i=0;i<size;i++){ if (data[i].equals(e)) return true; } return false; } // 查找數組中元素e所在的索引,如果不存在元素e,則返回-1 public int find(E e){ for (int i=0;i<size;i++){ if (data[i].equals(e)) return i; } return -1; } // 從數組中刪除index位置的元素, 返回刪除的元素 public E remove(int index){ if(index < 0 || index >= size) throw new IllegalArgumentException("Remove failed. Index is illegal."); E ret = data[index]; for (int i=index+1;i<size;i++){ data[i-1]=data[i]; } size--; if(size == data.length / 4 && data.length / 2 != 0) resize(data.length / 2); return ret; } // 從數組中刪除第一個元素, 返回刪除的元素 public E removeFirst(){ return remove(0); } // 從數組中刪除最后一個元素, 返回刪除的元素 public E removeLast(){ return remove(size-1); } // 從數組中刪除元素e public void removeElement(E e){ int index = find(e); if (index!=-1) remove(index); } @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(); } // 將數組空間的容量變成newCapacity大小 //動態數組 public void resize(int newCapacity){ E[] newData = (E[])new Object[newCapacity]; for (int i=0;i<size;i++){ newData[i] = data[i]; } data = newData; } }
這是一個動態數組的例子,可以根據數組元素個數的變化動態的擴容(2倍)或者減容!
代碼比較簡單,就不做解釋了!相信大家一定能夠看懂!
數組雖然簡單,但是大家還是需要重視一下!千萬不能小瞧了它!
好了,今天的文章寫到這里!重要的還是代碼。
