日常開發中不多使用數組了,至少我是不多使用了.....基本上都是List。底層也就是數組或者鏈表實現的。先本身實現一個動態數組。也就至關於一個簡單的ArrayList。其中應該有一些小bug,不過思路就是這樣的。代碼以下:數組
public class Arrays<E> {app
private E[] data;
//數組內元素的個數
private int size;
public Arrays(int capacity) {
this.data = (E[]) new Object[capacity];
this.size = 0;
}
public Arrays() {
this(10);
}
/**向某個索引位置添加元素
* @param index
* @param e
*/
public void add(int index,E e){
if (index > size|| index < 0){
throw new IllegalArgumentException("failed add,required index < array.length and index > 0");
}
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++;
}
/**移除某個位置的元素
* @param index
*/
public void remove(int index){
if (index >= size || index < 0){
throw new IllegalArgumentException("failed remove,required index < array.length and index > 0");
}
for (int i = index; i < size-1; i++) {
data[i] = data[i+1];
}
size--;
//當size = data.length/4纔對數組進行縮小,實現了一個Lazy的效果,防止出現極端的O(n)複雜度狀況
if (size == data.length/4){
resize(data.length/2);
}
}
/**數組擴容
* @param newCapacity
*/
private void resize(int newCapacity) {
E[] newData = (E[]) new Object[newCapacity];
for (int i = 0; i< data.length; i++) {
newData[i] = data[i];
}
data = newData;
}
//向數組內的開始插入元素
public void addFirst(E e){
add(0,e);
}
//向數組內末尾添加元素
public void addLast(E e){
add(size,e);
}
//獲取制定位置的元素
public E get(int index){
if (index < 0 || index >= size){
throw new IllegalArgumentException("set failed,Index is illegal");
}
return data[index];
}
//修改制定位置的元素
public void set(int index,E e){
if (index < 0 || index >= size){
throw new IllegalArgumentException("set failed,Index is illegal");
}
data[index] = e;
}
//判斷數組內是否包含某個元素
public boolean contains(E e){
for (int i = 0; i < size; i++){
if (data[i].equals(e)){
return true;
}
}
return false;
}
//判斷數組是否爲空
public boolean isEmpty(){
return size ==0;
}
//獲取數組內的元素個數
public int getSize(){
return this.size;
}
//獲取數組的容量
public int getLength(){
return this.data.length;
}
複製代碼
}測試
public static void main(String[] args) {
Arrays<Integer> arr = new Arrays<Integer>(10);
System.out.println("數組的長度:"+arr.getLength()+" 數組內的元素個數:"+arr.getSize());
//添加元素時,超過數組當前長度,數組自動擴容
for (int i = 0; i < 11; i++){
arr.add(i,i);
}
System.out.println(arr.contains(1));
System.out.println("數組的長度:"+arr.getLength()+" 數組內的元素個數:"+arr.getSize());
//移除一個元素,數組長度沒有當即縮小實現了Lazy效果
arr.remove(0);
System.out.println("數組的長度:"+arr.getLength()+" 數組內的元素個數:"+arr.getSize());
}
複製代碼
輸出內容:
數組的長度:10 數組內的元素個數:0
true
數組的長度:20 數組內的元素個數:11
數組的長度:20 數組內的元素個數:10
ui