import java.util.Arrays;
public class MyContainer {
public static void main(String[] args) {
IContainer<String> myCon = new ArrayList<String>(5);
for (int i=0; i<=12; i++) {
myCon.add("DATA " + (i + 1));
}
for (int i=0; i<myCon.size(); i++) {
System.out.println(myCon.get(i));
}
}
}
interface IContainer<T> {
public void add(T obj);
public T get(int index);
public int size();
}
class ArrayList<T> implements IContainer<T> {
private Object[] data = null;
private int n = 0;//计数器
public ArrayList() {
data = new Object[10];
}
public ArrayList(int capacity) {
data = new Object[capacity];
}
public void add(T obj) {
// 先判断是否扩容
capaUp(n+1); //为何变为n++即越界? 答:n+1没有赋值,若用n++计数器自增,使 data[n++] = obj;越界
data[n++] = obj;//为何定义为 n++; data[n] = obj;即越界? 答:此处应使用n自增前的值,此种写法n将使用自增后的值,造成越界
}
private void capaUp(int x) {
if (x > data.length) {
data = Arrays.copyOf(data,data.length+10);
}
}
@SuppressWarnings("unchecked")//注解:屏蔽警告 Object强转为T
public T get(int index) {
return (T)data[index];
}
public int size() {
return n;
}
}
|
|