class MyContainer
{
private Object[] arr = new Object[10];
/**计数器*/
private int index = 0;
public void add(Object obj){
if(arr.length == index){
Object[] temp = new Object[arr.length * 2];
//把原来容器里面的数据赋值给新的容器temp
for(int i=0; i<arr.length; i++){
temp[i]=arr[i];
}
arr=temp;
}
arr[index++] = obj;
}
public int size(){
return index;
}
/**
获取指定索引位置的元素
{2,0,0,0,0}
*/
public Object get(int index){
if(index >= this.index){
return null;
}
return arr[index];
}
public static void main(String[] args){
MyContainer c = new MyContainer();
for(long i=0; i<100; i++){
c.add("hello,"+i);
}
for(int i=0; i<c.size(); i++){
System.out.println(c.get(i));
}
System.out.println(c.size());
}
} |
|