模拟ArrayList容器的底层实现
package com.bjsxt.myCollection;
/**
* 模拟实现JDK中提供的ArrayList类
*
*/
public class MyArrayList {
Object[] value;
int size;
public MyArrayList() {
// value = new Object[16];
this(16);
}
public MyArrayList(int size) {
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 自动生成的 catch 块
e.printStackTrace();
}
}
return value[index];
}
public static void main(String args[]) {
MyArrayList list = new MyArrayList(2);
list.add("fff");
list.add(new Human("鹿迅"));
list.add("sdfgsd");
System.out.println(((Human) list.get(1)).getName());
}
}
posted on 2016-03-14 16:37 1130136248 阅读(79) 评论(0) 收藏 举报
浙公网安备 33010602011771号