匿名内部类,常常被用来实现某个接口。
import java.util.Enumeration;
public class DynamicArray {
private Object[] array = null;
private int count = 0;
/**
* 构造一个指定大小的数组
* */
public DynamicArray(int size) {
if(size <= 0) {
throw new IllegalArgumentException("size must > 0");
} else {
array = new Object[size];
}
}
/**
* 添加元素
* */
public int add(Object obj) {
if(count == array.length) {
Object[] newArray = new Object[array.length * 2 + 1];
for(int i=0;i<array.length;i++) {
newArray[i] = array[i];
}
array = newArray;
}
array[count++] = obj;
return count;
}
/**
* 通过Enumeration来取出元素
*
* */
public Enumeration getEnumeration() {
return new Enumeration() {
private int index = 0;
@Override
public boolean hasMoreElements() {
return index < count;
}
@Override
public Object nextElement() {
return array[index++];
}
};
}
public static void main(String[] args) {
DynamicArray da = new DynamicArray(5);
for(int i=0;i<5;i++) {
da.add(new Integer(i));
}
for(Enumeration e = da.getEnumeration(); e.hasMoreElements(); ) {
System.out.println(e.nextElement());
}
}
}