/**
* 动态数组
* @param <T>
*/
public class Array<T> {
private T [] data;
private int capacity;//容量
private int size;// 数组数据大小
public Array(int capacity){
data = (T[]) new Object[capacity];
size = 0;
this.capacity = capacity;
}
public Array(){
this(10);
}
public int getSize(){
return size;
}
public int getCapacity(){
return capacity;
}
public boolean isEmpty(){
return size == 0;
}
public void add(int index, T element){
if (index < 0 || index > size)
throw new IllegalArgumentException("index 越界 ");
for (int i = size; i > index; i--){
data[i] = data[i-1];
}
data[index] = element;
size ++;
if (size == capacity)
resize(capacity * 2);
}
public void addFirst(T element){
this.add(0,element);
}
public void addLast(T element){
this.add(size,element);
}
public T get(int index){
if (index < 0 || index >= size)
throw new IllegalArgumentException("index 越界 ");
return data[index];
}
public T remove(int index){
T element = get(index);
for (int i = index ; i < size; i++)
data[i] = data[i +1];
size --;
if (size < capacity/4 && capacity/2 > 0)
resize(capacity/2);
return element;
}
public T removeLast(){
return remove(size -1);
}
public T removeFirst(){
return remove(0);
}
@Override
public String toString(){
StringBuilder ret = new StringBuilder();
ret.append("Array capacity: " +capacity + " size: " +size +"\n");
ret.append("[");
for (int i = 0 ; i< size; i++){
ret.append(data[i]);
if (i != size-1)
ret.append(",");
}
ret.append("]");
return ret.toString();
}
//给数组动态扩容或缩容
public void resize(int newCapacity){
T [] newArray = (T[]) new Object[newCapacity];
for (int i = 0; i < size; i++ )
newArray[i] = data[i];
this.data = newArray;
this.capacity = newCapacity;
}
}