ArrayList非常相似于Array,但是当列表中的对象数量增加时,它提供动态空间分配的功能。 在Array对象中,需要在初始化时提供大小,但ArrayList不需要。 实际上,当初始化ArrayList时,它会自动将其容量分配给10。
使用Array实现ArrayList
在Array之上实现ArrayList。 所以在这里尝试使用Array实现自定义ArrayList并提供基本功能,如get(index),add(object)和remove(index)。
public class MyArrayList {
private static final int SIZE_FACTOR=5;
private Object data[];
private int index;
private int size;
public MyArrayList(){
this.data=new Object[SIZE_FACTOR];
this.size=SIZE_FACTOR;
}
public void add(Object obj){
System.out.println("index:"+this.index+"size:"+this.size+"data size:"+this.data.length);
if(this.index==this.size-1){
//we need to increase the size of data[]
increaseSizeAndReallocate();
}
data[this.index]=obj;
this.index++;
}
private void increaseSizeAndReallocate() {
this.size=this.size+SIZE_FACTOR;
Object newData[]=new Object[this.size];
for(int i=0; i
newData[i]=data[i];
}
this.data=newData;
System.out.println("***index:"+this.index+"size:"+this.size+"data size:"+this.data.length);
}
public Object get(int i) throws Exception{
if(i>this.index-1){
throw new Exception("ArrayIndexOutOfBound");
}
if(i<0){
throw new Exception("Negative Value");
}
return this.data[i];
}
public void remove(int i) throws Exception{
if(i>this.index-1){
throw new Exception("ArrayIndexOutOfBound");
}
if(i<0){
throw new Exception("Negative Value");
}
System.out.println("Object getting removed:"+this.data[i]);
for(int x=i; x
data[x]=data[x+1];
}
this.index--;
}
public static void main(String[] args) throws Exception {
MyArrayList mal = new MyArrayList();
mal.add("0");
mal.add("1");
mal.add("2");
mal.add("3");
mal.add("4");
mal.add("5");
mal.add("6");
mal.add("7");
mal.add("8");
mal.add("9");
mal.remove(5);
System.out.println(mal.get(7));
}
}
这只是使用Array来实现ArrayList的基本功能,并了解它是如何实现的。出于开发目的,请使用随JDK提供的ArrayList。
下面是执行上述程序时产生的输出结果:
yiibai:Downloads yiibai$ javac MyArrayList.java
yiibai:Downloads yiibai$ java MyArrayList
index:0size:5data size:5
index:1size:5data size:5
index:2size:5data size:5
index:3size:5data size:5
index:4size:5data size:5
***index:4size:10data size:10
index:5size:10data size:10
index:6size:10data size:10
index:7size:10data size:10
index:8size:10data size:10
index:9size:10data size:10
***index:9size:15data size:15
Object getting removed:5
8
yiibai:Downloads yiibai$