package bjsxt.collection;
/*
* 实现ArrayList的部分方法
*/
public class TestArrayList {
private Object[] elementData; //初始化数组
private int size; //数组里元素的数量
public int size() {
return size;
}
public TestArrayList() { //默认数组长度
this(10);
}
public TestArrayList(int initialCapacity) {
if(initialCapacity<0) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
elementData=new Object[initialCapacity];
}
public void add(Object obj) {
//数组扩容和数据的拷贝
if(size==elementData.length) {
Object[] newArray=new Object[size+1];
for(int i=0;i<size;i++) {
newArray[i]=elementData[i];
}
elementData=newArray;
}
elementData[size++]=obj;
}
public boolean isEnpty() {
return size==0;
}
public Object get(int index) {
if(index<0||index>=size) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return elementData[index];
}
public void remove(int index) {
//删除指定位置的对象
RangeCheck(index);
for(int i=index;i<size-1;i++) {
elementData[i]=elementData[i+1];
}
elementData[--size]=null;
}
public void RangeCheck(int index) {
if(index<0||index>=size) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TestArrayList list=new TestArrayList(3);
list.add("333");
list.add("333");
list.add("333");
list.add("333");
System.out.println(list.size());
System.out.println(list.isEnpty());
System.out.println(list.get(2));
list.remove(3);
}
}