顺序表实现


public class MyArrayList<E> {



Object [] data=null; //用来保存此队列中内容的数组

int current; // 保存当前为第几个元素
int capacity; // 表示数组大小的指标

public MyArrayList(){
this(10);
}


public MyArrayList(int initalSize){
if(initalSize<0){
throw new RuntimeException("数组大小错误"+initalSize);
}else{
this.data=new Object[initalSize];
this.current=0;
this.capacity=initalSize;

}
}


public boolean add(E e){
ensureCapacity(this.current);
this.data[this.current]=e;
this.current++;
return true;
}


private void ensureCapacity(int cur){
if(cur==this.capacity){
this.capacity=this.capacity+10;
System.out.println("做了增加容量操作!");
Object[] newdata=new Object[this.capacity];
for(int i = 0 ; i<cur;i++){
newdata[i]=this.data[i];
}
this.data=newdata;
}
}

@SuppressWarnings("unchecked")
public E get(int index){
validateIndex(index);

return (E)this.data[index];

}


private void validateIndex(int index){
if(index<0 || index>this.current){
throw new RuntimeException("数组index错误"+index);
}
}


public boolean insert(int index,E e){

validateIndex(index);

Object [] tem=new Object[this.capacity];

for(int i=0;i<this.current;i++){
if(i<index){
tem[i]=this.data[i];
}else if(i==index){
tem[i]=e;
}else if(i>index){
tem[i]=this.data[i-1];
}
}
this.data=tem;

return true;
}



public boolean delete(int index){
validateIndex(index);

Object[] tem=new Object[this.capacity];

for(int i = 0 ; i<this.current;i++){
if(i<index){
tem[i]=this.data[i];
}else if(i==index){

tem[i]=this.data[i+1];
}else{
tem[i]=this.data[i+1];
}
}

this.data=tem;

return true;

}

/**
* @param args
*
* author:jack_lcz
*
* date: 2011-08-30
*/
public static void main(String[] args) {
// TODO Auto-generated method stub


MyArrayList ml=new MyArrayList();

ml.add("梁栩彬");
ml.add("梁承祝");
ml.delete(0);
System.out.print(ml.get(0));



}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值