java自动实例化List AutoArrayList



import java.util.ArrayList;

public class AutoArrayList extends ArrayList {

private Class itemClass;

private AutoArrayList(Class itemClass) {
this.itemClass = itemClass;
}

public Object get(
int index) {
try {
if (index >= size()) {
add(itemClass.newInstance());
}
} catch (Exception e) {
e.printStackTrace();
}
return super.get(index);
}

public static void main(
String[] args) {

AutoArrayList autoArrayList = new AutoArrayList(String.class);

Object t0 = autoArrayList.get(0);
Object t1 = autoArrayList.get(1);

System.out.println("t0=" + t0);
System.out.println("t1=" + t1);
}
}

猜你喜欢

转载自vernonchen163.iteye.com/blog/2094573