package SequenceList;
public
class SequenceList {
public int length=10; //初始化数组的大小
private int current; //总是指向数组的最后一个元素
private Object[] data; //存放数组元素
public SequenceList(){ //初始化
this.data=new Object[length];
current=0;
}
public void add(Object value){ //在末尾添加元素
ensurecap();
data[current]=value;
current++;
}
public void add(int pos,Object obj){ //在指定的位置添加元素
ensurecap();
if(pos>current){
System.out.println("the pos is not correct!");
}
else{
for(int i=current;i>pos-1;i--){
data[i]=data[i-1];
}
data[pos-1]=obj;
}
current++;
}
public void delete(int pos){ //删除某个位置的元素
if(pos>current||pos<1){
System.out.println("the pos is not correct!");
}else{
for(int i=pos-1;i<current;i++){
data[i]=data[i+1];
}
current--;
}
}
public Object get(int pos){
return data[pos-1];
}
public int getSize(){
return current;
}
public void display(){
for(int i=0;i<current;i++){
System.out.print(data[i]+" ");
}
}
public void ensurecap(){ //只要数组满了就扩容,而不是等到插入的时候才扩容
if(current==length){
Object[] data_new=new Object[length*2];
for(int i=0;i<length;i++){
data_new[i]=data[i];
}
data=data_new;
length=2*length;
}
}
public static void main(String[] args) {
SequenceList sl=new SequenceList();
sl.add(1);
sl.add(2);
sl.add(3);
sl.add(4);
sl.add(5);
sl.add(6);
sl.add(7);
sl.add(8);
sl.add(9);
sl.add(10);
sl.add(11);
sl.add(12);
sl.display();
System.out.println(" size is:"+sl.getSize());
sl.delete(1);
sl.display();
System.out.println(" size is:"+sl.getSize());
sl.delete(5);
sl.display();
System.out.println(" size is:"+sl.getSize());
sl.add(9, 7);
sl.display();
System.out.println(" size is:"+sl.getSize());
}
}