package sjjg;
/**
* 可变数组
* @author wl
*
*/
public class Array<E> {
//存储数据数组
private E[] data;
//size
private int size;
/*
* 无参方法
*/
public Array() {
data = (E[]) new Object[10];
size=0;
}
public Array(int capacity ) {
data = (E[])new Object[capacity];
size=0;
}
//获取数据的大小
public int getSize(){
return size;
}
//获取数组的容量
public int getCapacity(){
return data.length;
}
//判断是否为空
public boolean isEmpty(){
return size==0;
}
//向所有元素后添加元素
public void addLast(E e){
if(size == data.length)
resize();
add(size,e);
}
public void addFirst(E e){
add(0,e);
}
public void add(int index,E e){
if(size == data.length)
resize();
for (int i=size-1;i>=index;i--){
data[i+1]=data[i];
}
data[index]=e;
size++;
}
//获取index
public E get(int index){
return data[index];
}
//修改索引
public void set(int index,E e){
data[index]=e;
}
//是否包含
public boolean contain(E e){
for(int i=0;i<size;i++){
if(data[i]==e)
return true;
}
return false;
}
//find
public int find(E e){
for(int i=0;i<size;i++){
if(data[i]==e)
return i;
}
return -1 ;
}
//remove
public E remove(int index){
E ret =data[index];
for(int i=index+1;i<size;i++){
data[i-1]=data[i];
}
size--;
return ret;
}
//remove first
public E removeFirst(){
return remove(0);
}
public E removeLast(){
return remove(size-1);
}
public void removeE(E e){
int index=find(e);
if(index!=-1){
remove(index);
}
}
//resize
public void resize(){
E[] newData = (E[]) new Object[2*data.length] ;
for(int i=0;i<data.length;i++)
newData[i] = data[i];
data = newData;
}
@Override
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();
}
}