// MyArray 为泛型类的名称
// E 为泛型类的形参列表, 是一种类型
public class MyArray<E> {
}
泛型的使用
// MyArray 为泛型类的名称
// E 为泛型类的形参列表, 是一种类型
public class MyArray<E> {
public E[] array = null;
public int size;
public int capacity;
public MyArray(int capacity) {
this.array = (E[]) new Object[capacity];
this.size = 0;
this.capacity = capacity;
}
public void add(E data) {
if (size < capacity) {
array[size++] = data;
}
}
public E get(int index) {
return this.array[index];
}
public int size() {
return this.size;
}
}
public class Test {
public static void main(String[] args) {
MyArray<String> myArray = new MyArray<String>(2);
myArray.add("12");
myArray.add("34");
System.out.println(myArray.size());
System.out.println(myArray.get(0));
}
}