仿jdk的ArrayList实现

package cn.lmj201401;
@SuppressWarnings("unchecked")
public class MyArrayList<E>
{
private int capacity = 10;
private int size = 0;
private E[] values = null;

//通过构造器生成默认的10个容量
public MyArrayList()
{
values = (E[]) new Object[capacity];
}

//通过构造器生成指定容量大小的初始化集合元素个数
public MyArrayList(int capacity)
{
this.capacity = capacity;
values = (E[]) new Object[capacity];
}

//增加元素
public void add(E e)
{
if(e == null)
{
throw new RuntimeException("The value should not null");
}
if(size >= capacity)
{
//增加集合里面维护的数组长度
addCapacity();
}
values[size] = e;
try
{
//Thread.sleep(1000);
size+=1;
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
}

//获取元素
public E get(int index)
{
if(index >= this.size)
{
throw new RuntimeException("The index of"+index+"is out of band!");
}
return values[index];
}

//删除元素
public void remove(int index)
{
if(index >= this.size)
{
throw new RuntimeException("The index of"+index+"is out of band!");
}
for(int i = index;i<size-1;i++)
{
values[i] = values[i+1];
}
values[size-1] = null;
size--;
}

//打印元素
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("[");
for(int i = 0;i<size;i++)
{
sb.append(values[i].toString()+",");
}
return sb.substring(0,sb.length()-1)+"]";
}


//增加集合里面维护的数组长度
private void addCapacity()
{
this.capacity = capacity*2;
E[] values_temp = (E[]) new Object[capacity];
System.arraycopy(values,0,values_temp,0,size);
values = values_temp;
}

public void print()
{
for(int i = 0;i<size;i++)
{
System.out.println(values[i]);
}
}

public static void main(String[] args)
{
MyArrayList<String> list = new MyArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("7");
list.add("8");
list.add("9");
list.add("10");
list.add("11");
list.remove(7);
System.out.println(list.size);
System.out.println(list);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值