Data Structure.Array

数组成员

public class Array<E> { //使用泛型

    private E[] data; //建立数组
    private int size;
}

构造数组

// 构造函数,传入数组的容量capacity构造Array
public Array(int capacity){
    data = (E[])new Object[capacity]; //E[]强制类型转换
    size = 0;
}

// 无参数的构造函数,默认数组的容量capacity=10
public Array(){
    this(10);
}

获取容量

// 获取数组的容量 为之后“动态数组”提供条件
public int getCapacity(){
    return data.length;
}

添加元素

// 在index索引的位置插入一个新元素e
public void add(int index, E e){

    if(index < 0 || index > size)
        throw new IllegalArgumentException("Add failed. Illegal scope.");

    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 ++; //维护元素个数
}

删除元素

// 从数组中删除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 --;
    data[size] = null; // loitering objects

    if(size == data.length / 4 && data.length / 2 != 0) //惰性操作 避免极端情况使复杂度突增
        resize(data.length / 2); // 2/4 == 0
    return ret;
}

修改容量

private void resize(int newCapacity){

    E[] newData = (E[])new Object[newCapacity];
    for(int i = 0 ; i < size ; i ++)
        newData[i] = data[i];
    data = newData;
}

输出格式

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();
}

猜你喜欢

转载自blog.csdn.net/weixin_43960884/article/details/88786448