package generics; import java.util.Arrays; // 泛型类 -> 动态数组 public class DynamicArray<E>{ // field private static final int DEFAULT_CAPACITY = 10; private int size; private Object[] elementData; // constructor 构造函数 public DynamicArray(){ this.elementData = new Object[DEFAULT_CAPACITY]; } // method // 确保数组有足够的长度 private void ensureCapacity(int minCapacity){ int oldCapacity = elementData.length; if(oldCapacity >= minCapacity){ return; } int newCapacity = oldCapacity * 2; if(newCapacity < minCapacity){ newCapacity = minCapacity; } elementData = Arrays.copyOf(elementData, newCapacity); } // 添加元素 public void add(E e){ ensureCapacity(size + 1); elementData[size++] = e; } // 搜索索引 public E get(int index){ return (E)elementData[index]; } // 返回大小 public int size(){ return size; } // 设置元素 public E set(int index, E element){ E oldValue = get(index); elementData[index] = element; return oldValue; } // 泛型方法 // 类型参数为T,放在返回类型前面 public static <T> int indexOf(T[] arr, T elm){ for(int i = 0; i < arr.length; i++){ if(arr[i].equals(elm)){ return i; } } return -1; } // 通配符 ? // <? extends E> -> 有限通配符,匹配E或E的某个子类型,用于实例化类型参数,未知具体类型 public void addAllWailcard(DynamicArray<? extends E> c){ for(int i = 0; i < c.size; i++){ add(c.get(i)); } } // <T extends E> -> 用于定义类型参数,声明一个类型参数T,可放在泛型类定义中类名的后面、泛型方法返回值前面 public <T extends E> void addAll(DynamicArray<T> c){ for(int i = 0; i < c.size; i++){ add(c.get(i)); } } // <? super E> -> 超类型通配符,可以更灵活地写入 public void copyTo(DynamicArray<? super E> dest){ for(int i = 0; i < size; i++){ dest.add(get(i)); } } @Override public String toString(){ return Arrays.toString(elementData); } // __main__ public static void main(String[] args){ DynamicArray<String> da = new DynamicArray<String>(); da.add("Hello"); da.add("Hola"); da.add("你好"); System.out.println(da.get(2)); System.out.println(da.size()); System.out.println(da.set(1, "konnichiwa")); System.out.println(da.get(1)); System.out.println(indexOf(new Integer[]{1, 3, 4} , 1)); System.out.println(indexOf(new String[]{"Hello", "Hola", "你好"} , "hola")); System.out.println(indexOf(da.elementData, "你好")); System.out.println(da.toString()); DynamicArray added = new DynamicArray(); added.add("Hola"); added.add("Aniaseyou"); da.addAllWailcard(added); System.out.println(da.toString()); da.addAll(added); System.out.println(da.toString()); DynamicArray<Integer> ints = new DynamicArray<Integer>(); ints.add(100); ints.add(34); DynamicArray<Number> nums = new DynamicArray<Number>(); ints.copyTo(nums); System.out.println(ints.toString()); System.out.println(nums); } }