天天看點

java動态數組_Java動态數組

packagegenerics;importjava.util.Arrays;//泛型類 -> 動态數組

public class DynamicArray{//field

private static final int DEFAULT_CAPACITY = 10;private intsize;privateObject[] elementData;//constructor 構造函數

publicDynamicArray(){this.elementData = newObject[DEFAULT_CAPACITY];

}//method//確定數組有足夠的長度

private void ensureCapacity(intminCapacity){int oldCapacity =elementData.length;if(oldCapacity >=minCapacity){return;

}int newCapacity = oldCapacity * 2;if(newCapacity

newCapacity=minCapacity;

}

elementData=Arrays.copyOf(elementData, newCapacity);

}//添加元素

public voidadd(E e){

ensureCapacity(size+ 1);

elementData[size++] =e;

}//搜尋索引

public E get(intindex){return(E)elementData[index];

}//傳回大小

public intsize(){returnsize;

}//設定元素

public E set(intindex, E element){

E oldValue=get(index);

elementData[index]=element;returnoldValue;

}//泛型方法//類型參數為T,放在傳回類型前面

public static intindexOf(T[] arr, T elm){for(int i = 0; i < arr.length; i++){if(arr[i].equals(elm)){returni;

}

}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,可放在泛型類定義中類名的後面、泛型方法傳回值前面

public void addAll(DynamicArrayc){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));

}

}

@OverridepublicString toString(){returnArrays.toString(elementData);

}//__main__

public static voidmain(String[] args){

DynamicArray da = new DynamicArray();

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= newDynamicArray();

added.add("Hola");

added.add("Aniaseyou");

da.addAllWailcard(added);

System.out.println(da.toString());

da.addAll(added);

System.out.println(da.toString());

DynamicArray ints = new DynamicArray();

ints.add(100);

ints.add(34);

DynamicArray nums = new DynamicArray();

ints.copyTo(nums);

System.out.println(ints.toString());

System.out.println(nums);

}

}