集合ArrayList中的算法

//ArrayList對象比較可直接用equals比較,它會比較到每一個值


//算法代碼

public class HighArray {

int[] a = new int[5];
int n = 0;


/**
* 插入元素時,如果元素的索引快到數組長度臨界值,增加數組長度

* @param value
*/
public void insert(int value) {
a[n] = value;
n++;
if (n == a.length - 1) {
int[] b = new int[a.length * 2];
for (int i = 0; i < n; i++) {
b[i] = a[i];
}
// 引用
// b數組的引用,交給a,
// b數組的引用賦值給a,a指向b數組
a = b;
}
}


// 查找
public boolean find(int key) {
int i;
for (i = 0; i < n; i++) {
if (a[i] == key) {
break;
}
}
if (i <= n) {
return true;


} else {
return false;
}


}


/**
* 根據key找到其座標
*/
public int findindex(int key) {
int i;
for (i = 0; i < n; i++) {
if (a[i] == key) {
return i;
}
}


return -1;


}


// 遍歷
public void dissplay() {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
}


// 刪除
public void deleteElem(int key) {
// 基本刪除元素會有空間浪費
// int delindex=findindex(key);
// a[delindex]=0;
// 節省空間方式:
// 要刪除的這個下標位其後的數據
// 1.找的要刪除數據的下標
int delindex = findindex(key);
// 2.從這個要刪除下標+1開始循環
for (int i = delindex + 1; i < n; i++) {
a[i - 1] = a[i];
a[i] = 0;
}
if (delindex > -1) {
n--;
}
// 3.遍歷到每個元素,都能向前移動
}

}


//調用上述代碼

HighArray arr = new HighArray();
// 添加
for (int i = 0; i < 15; i++) {
arr.insert(i);
}
arr.insert(25);
// 取得元素
arr.dissplay();


// ArrayList添加、查找
ArrayList list = new ArrayList();
for (int i = 0; i < 5; i++) {
// list.add(i, i);
list.add(i);


}
System.out.println(list.contains(4));


// 查找
boolean isfound = arr.find(15);
if (isfound) {
System.out.println("found seachkey");
} else {
System.out.println("Catn't found");
}
// 查找到key的座標
System.out.println(arr.findindex(3));


// 刪除
arr.deleteElem(2);
arr.dissplay();
}
}

//用ArraryList的方法如何實現上述的操作

//插入
ArrayList arr=new ArrayList();
arr.add(50);
for (int i = 0; i <15; i++) {
arr.add(i);
}

//遍歷
System.out.println(arr.toString());


//查找
System.out.println(arr.contains(10));
//查找到其座標
System.out.println(arr.indexOf(5));
//刪除元素remove中參數是元素的位置
arr.remove(5);
//遍歷
System.out.println(arr.toString());

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