泛型的代碼

package cn.java.jixun.lesson21;

public class NetJavaList<E> {
// 創建一個初始數組
private Object[] array = new Object[0];

/**
* 向隊列中添加元素
*
*/
public void add(E str) {
// 創建一個新的數組,長度是array數組的長度+1
Object[] temp = new Object[array.length + 1];
// 將array數組中的元素添加到新的數組中
for (int i = 0; i < array.length; i++) {
// 賦值
temp[i] = array[i];
}
// 將要添加的元素添加到新的數組的末尾
temp[array.length] = str;
// 將新建的數組賦值給array
array = temp;
}

/**
* 返回自定義隊列的長度
*
*
*/
/**
* 在指定位置添加元素, 思路:取得指定位置之前的元素,在固定位置加入元素
*/
public void add(String add, int index) {
Object[] temp = new Object[array.length + 1];
// 取得指定位置
for (int i = 0; i < index; i++) {
temp[i] = array[i];
}
temp[index] = add;
for (int i = index + 1; i < temp.length; i++) {
temp[i] = array[i - 1];

}
array = temp;

}

/**
* 刪除某一位置的元素
*
* @return
*/

public void remove(int index) {
Object[] temp = new Object[array.length - 1];
for (int i = 0; i < index; i++) {
temp[i] = array[i];

}
for (int i=index+1;i<temp.length;i++){
temp[i]=array[i+1];
}
array=temp;

}


public int size() {
return array.length;
}

/**
* 獲取指定位置的元素
*
*/
public E get(int index) {
return (E) array[index];

}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章