package com.MyArray;
/**
* 模拟实现JDK中的Arrilist类
* @author Administrator
*
*/
public class MyArraylist {
Object[] value;
private int size;
public int size()
{
return size;
}
/*构造器*/
public MyArraylist() {
// TODO Auto-generated constructor stub
this(16);
}
public MyArraylist(int size) {
// TODO Auto-generated constructor stub
value = new Object[size];
}
public void add(Object obj) {
value[size] = obj;
size++;
if (size>=value.length) {
//装不下了
int newCapacity = value.length*2;
Object[] newList = new Object[newCapacity];
for (int i = 0; i < value.length; i++) {
newList[i]=value[i];
}
value = newList;
}
}
public Object get(int index){
if(index<0||index>size-1){
try {
throw new Exception();//手动抛出异常
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return value[index];
}
public static void main(String[] args) {
MyArraylist list = new MyArraylist(2);
list.add("add");
list.add(new Human("高琪"));
list.add("bbb");
Human h =(Human) list.get(1);
System.out.println(h.getName());
System.out.println(list.get(2));
//System.out.println(list.get(3));
System.out.println(list.size());
}
}
高琪-模拟实现JDK中的Arrilist类
最新推荐文章于 2021-11-01 15:43:40 发布