java数组数据结构_Java数据结构之数组
自定義數組(面向對象編程):
直接上代碼:package?com.xingej.algorithm.datastructure.array;
/**
*?面向對象編程
*
*?自定義類數組
*
*?你一定要明白,這是在JDK基礎之上的封裝,要學會這種思路,其他框架如netty?也是在前者的基礎上封裝而來的,如有一
*
*?部分是封裝的線程池
*
*?@author?erjun?2017年11月28日?下午9:42:10
*/
public?class?MyArray?{
//?定義的數據結構,類型是?數組
//?這是最核心的組件,其他都是圍繞這個來進行操作的
private?long[]?arr;
//?表示有效數據的長度,也就是說,數組里有多少個數組
private?int?elements;
public?MyArray()?{
//?默認可以存儲50個數字
arr?=?new?long[50];
}
public?MyArray(int?maxsize)?{
arr?=?new?long[maxsize];
}
//?插入數據
public?void?insert(long?value)?{
arr[elements]?=?value;
//?每次插入數據,都會自增一次
elements++;
}
//?根據索引,來查找數據
public?long?get(int?index)?{
if?(index?>=?elements?||?index?
throw?new?ArrayIndexOutOfBoundsException();
}
return?arr[index];
}
//?顯示數據,也就是,打印數組里的內容
public?void?display()?{
//?說明,此時數組里,還沒有內容呢
if?(elements?<=?0)?{
return;
}
System.out.print("[?");
for?(int?i?=?0;?i?
System.out.print(arr[i]?+?"?");
}
System.out.println("]");
}
//?根據輸入的值,來返回?索引值
public?int?getIndexByValue(long?value)?{
int?i?=?0;
for?(;?i?
if?(arr[i]?==?value)?{
//?如果找到的話,就立即返回索引值
return?i;
}
}
return?-1;
}
//?根據索引值,來刪除數組里的元素
public?void?delete(int?index)?{
if?(index?>=?elements?||?index?
throw?new?ArrayIndexOutOfBoundsException();
}
//?將后面的元素,往前移動
for?(int?i?=?index;?i?
arr[i]?=?arr[i?+?1];
}
//?最后,將有效值,減一
elements--;
}
//?更新值
public?void?update(int?index,?long?newValue)?{
if?(index?>=?elements?||?index?
throw?new?ArrayIndexOutOfBoundsException();
}
arr[index]?=?newValue;
}
}
測試用例:package?com.xingej.algorithm.datastructure.array;
import?org.junit.Before;
import?org.junit.Test;
import?com.xingej.algorithm.datastructure.array.MyArray;
/**
*?面向對象編程,
*
*?也就是說,你操作的?都是對象,而非基本數據類型了
*
*
*?@author?erjun?2017年11月28日?下午9:59:36
*/
public?class?MyArrayTest?{
private?MyArray?myArray;
@Before
public?void?init()?{
myArray?=?new?MyArray();
testInsert();
}
//?插入數據測試
@Test
public?void?test()?{
myArray.insert(20);
System.out.println("----:\t"?+?myArray.get(0));
}
@Test
public?void?testInsert()?{
myArray.insert(20);
myArray.insert(10);
myArray.insert(5);
myArray.insert(30);
}
//?顯示/打印數組里的內容
@Test
public?void?testDisplay()?{
myArray.display();
}
//?顯示/打印數組里的內容
@Test
public?void?testGetIndexByValue()?{
System.out.println("---索引值是:\t"?+?myArray.getIndexByValue(20));
}
//?根據下標,來刪除指定位置的元素
@Test
public?void?testDelete()?{
System.out.println("---刪除之前打印數組里的元素------");
myArray.display();
myArray.delete(5);
System.out.println("---刪除之后打印數組里的元素------");
myArray.display();
}
@Test
public?void?testUpdate()?{
myArray.update(2,?100);
System.out.println("---更新之后的值----:\t"?+?myArray.get(2));
}
}
代碼已經上傳到git上了:
總結
以上是生活随笔為你收集整理的java数组数据结构_Java数据结构之数组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ax200网卡支持Linux吗,Deep
- 下一篇: postgre管理员 无法访问表_pos