仿jdk的ArrayList实现

来源:互联网 发布:ins注册提示网络错误 编辑:程序博客网 时间:2024/05/19 03:29
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
原创粉丝点击