这里先作为了解容器的起步,模拟一下ArrayList,后面在容器中会有更多的内容
package cn.itcast.java.test;
/**
* 模拟ArrayList
* @author Administrator
*
*/
public class MyArrayList {
private Object[] value;
private int size;
public MyArrayList(){
//value = new Object[10];
this(10);
}
public MyArrayList(int capacity){
value = new Object[capacity];
}
/*
* 返回容器的大小
*/
public int size(){
return size;
}
/*
* 判断容器是否为空
*/
public boolean isEmpty(){
return value.length == 0;
}
/*
* 添加元素
*/
public void add(Object obj){
value[size] = obj;
size++;
if(size>=value.length){
//扩容
int newCapacity = value.length*2+2;
Object[] newValue = new Object[newCapacity];
//数组拷贝
for(int i=0;i<value.length;i++){
newValue[i] = value[i];
}
value = newValue;
}
}
/*
* 根据索引返回元素
*/
public Object get(int index){
if(index<0||index>=value.length){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
return value[index];
}
public static void main(String[] args) {
MyArrayList list = new MyArrayList();
list.add("aa");
list.add(new Person("Gao"));
list.add(11);
System.out.println(list.get(0));
System.out.println(list.get(1));
System.out.println(list.size());
System.out.println(list.isEmpty());
}
}