1:靜態(tài)數(shù)組說明
先進行靜態(tài)數(shù)組(無法擴容)的練習(xí) 熟悉一個靜態(tài)數(shù)組的寫法
* 1:getLength() 獲取空間大小
* 2:getCount() 獲取已有個數(shù)
* 3:find(int index) 根據(jù)索引找到數(shù)據(jù)中的元素并返回
* 4:findAll() 查詢所有元素
* 5:insert(int value)在數(shù)組尾部插入元素
* 6:insertByIndex(int index, int value) 根據(jù)索引插入元素
* 7:deleteByIndex(int index) 根據(jù)索引刪除元素
2:代碼實戰(zhàn)
public class StaticArrayList {
//定義整型數(shù)據(jù)data保存數(shù)據(jù)
public int data[];
//定義數(shù)組長度
private int capacity;
//定義實際個數(shù)
private int count;
//構(gòu)造方法,定義數(shù)組大小
public StaticArrayList(int capacity) {
this.data = new int[capacity];
this.capacity = capacity;
//一開始一個數(shù)都沒有存所以為0
this.count = 0;
}
//獲取空間大小
public int getLength(){
return data.length;
}
//獲取已有個數(shù)
public int getCount(){
return count;
}
//根據(jù)索引找到數(shù)據(jù)中的元素并返回
public int find(int index) {
if (index < 0 || index >= count) {
return -1;
}
return data[index];
}
//查詢所有元素
public void findAll() {
for (int i = 0; i < count; ++i) {
System.out.print(data[i] + " ");
}
System.out.println();
}
//在數(shù)組尾部插入元素
public boolean insert(int value){
// 數(shù)組空間已滿
if (count == capacity) {
System.out.println("沒有可插入的位置");
return false;
}
data[count] = value;
++count;
return true;
}
//根據(jù)索引插入元素
public boolean insertByIndex(int index, int value) {
// 數(shù)組空間已滿
if (count == capacity) {
System.out.println("沒有可插入的位置");
return false;
}
// 如果count還沒滿,那么就可以插入數(shù)據(jù)到數(shù)組中
if (index < 0 || index > count) {
System.out.println("位置不合法");
return false;
}
// 位置合法
//需要從數(shù)組最大的索引位置開始 各向上挪動一位
//然后替換調(diào)需要插入的索引數(shù)據(jù)
for (int i = count; i > index; --i) {
data[i] = data[i - 1];
}
data[index] = value;
++count;
return true;
}
//根據(jù)索引刪除元素
public boolean deleteByIndex(int index) {
if (index < 0 || index >= count) {
return false;
}
//從刪除位置開始,將后面的元素向前移動一位
for (int i = index + 1; i < count; ++i) {
data[i - 1] = data[i];
}
--count;
return true;
}
}
3:代碼測試
private static void staticArrayListTest() {
StaticArrayList staticArrayList = new StaticArrayList(10);
System.out.println("空間大小 :" + staticArrayList.getLength());
//在末尾新增一個元素
staticArrayList.insert(1);
staticArrayList.insert(5);
staticArrayList.insert(10);
System.out.println("實際個數(shù) :" + staticArrayList.getCount());
System.out.println("測試查詢功能 存在則返回對應(yīng)值 不存在則返回 -1 :" + staticArrayList.find(3));
//隨機插入的元素必須在 等于或小于已有的實際個數(shù) 如此時就是[1,5,10] 即3
staticArrayList.insertByIndex(3, 666);
staticArrayList.findAll();
//測試按下標(biāo)插入 數(shù)據(jù)挪位功能
staticArrayList.insertByIndex(1, 999);
staticArrayList.findAll();
//測試按下標(biāo)刪除 數(shù)據(jù)挪位功能
staticArrayList.deleteByIndex(1);
staticArrayList.findAll();
}
項目連接
請配合項目代碼食用效果更佳:
項目地址:
https://github.com/hesuijin/hesuijin-algo
Git下載地址:
https://github.com.cnpmjs.org/hesuijin/hesuijin-algo.git
arrayCollection包
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。