学习数据结构系列(一)实现一个动态数组

301 阅读4分钟

平常开发中很少使用数组了,至少我是很少使用了.....基本上都是List。底层也就是数组或者链表实现的。先自己实现一个动态数组。也就相当于一个简单的ArrayList。其中应该有一些小bug,不过思路就是这样的。代码如下:

public class Arrays<E> {

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