首页 热点专区 小学知识 中学知识 出国留学 考研考公
您的当前位置:首页正文

c++基础-实现 Native 层的 ArrayList

来源:要发发知识网
#include "malloc.h"

//-------------------------------声明------------------------------//
template<class E>
class ArrayList {
private:
    E *array = NULL;
    //数组的长度
    int len = 0;
    //当前角标
    int index = 0;
public:
    ArrayList();

    ArrayList(int capacity);

    void add(E e);

    E remove(int index);

    E get(int index);

    ~ArrayList();

    int size();

private:
    void ensureCapacityInternal(int capacity);

    void grow(int capacity);
};

//-------------------------------实现------------------------------//
template<class E>
ArrayList<E>::ArrayList() {


};

template<class E>
ArrayList<E>::ArrayList(int capacity) {
    if (capacity < 0) {
        return;
    }
    this->len = capacity;
    this->array = (E *) malloc(sizeof(E));

};

template<class E>
ArrayList<E>::~ArrayList() {
    if (this->array) {
        free(this->array);
        this->array = NULL;
    }
};

template<class E>
int ArrayList<E>::size() {
    return this->index;
}

template<class E>
void ArrayList<E>::add(E e) {
    ensureCapacityInternal(index + 1);  // Increments modCount!!
    this->array[index++] = e;
}

template<class E>
void ArrayList<E>::ensureCapacityInternal(int capacity) {
    if (this->array == NULL) {
        capacity = 10;
    }
    if (capacity - len > 0) {
        //开辟新的数组
        grow(capacity);
    }
}

//扩容
template<class E>
void ArrayList<E>::grow(int capacity) {
    int new_len = len + (len >> 1);
    if (capacity > new_len) {
        new_len = capacity;
    }
    //创建新的数组
    E *newArray = (E *) malloc(sizeof(E) * new_len);
    if (this->array) {
        //原来的数据拷贝
        memcpy( newArray,this->array, sizeof(E) * index);//sizeof(E)拷贝的字节
        free(this->array);//防止内存泄露
    }
    this->array = newArray;
    this->len = new_len;
}
template<class E>
E ArrayList<E>::get(int index){
    return this->array[index];
}
template<class E>
E ArrayList<E>::remove(int index) {
    E old_value = this->array[index];
    // 计算出需要逻动的个数
    int numMoved = this->index - index - 1;

    // 从前面不断的逻动
    for (int i = 0; i < numMoved; ++i) {
        array[index + i] = array[index + i + 1];
    }

    this->index -= 1;
    return old_value;
}
#endif //NDK_ARRAYLIST_H
显示全文