数组作为Java最基本的数据结构在处理数据时具有广泛的应用,接下来将封装数组常用的增删查改方法,以便掌握对数组的基本操作。
package com.test.array;
/*
* 自定义的数组封装类
*/
public class MyArray {
private long[] arr;
//表示有效数据的长度
private int elements;
public MyArray(){
arr = new long[50];
}
public MyArray(int maxsize){
arr = new long[maxsize];
}
/*
* 添加数据
*/
public void insert(long value){
arr[elements] = value;
elements++;
}
/*
* 有序添加数据
*/
public void insertBySort(long value){
int i;
for(i = 0;i < elements; i++){
if(arr[i] > value){
break;
}
}
for(int j = elements; j > i; j--){
arr[j] = arr[j - 1];
}
arr[i] = value;
elements++;
}
/*
* 显示数据
*/
public void display(){
System.out.print("[");
for(int i = 0;i < elements; i++){
System.out.print(arr[i]+" ");
}
System.out.println("]");
}
/*
* 根据值查找数据(线性查找)
*/
public int searchByValue(long value){
int i;
for(i = 0;i < elements; i++){
if(value == arr[i]){
break;
}
}
if(i == elements){
return -1;
}else{
return i;
}
}
/*
* 根据值查找数据(二分法查找)
*/
public int binarySearch(long value){
int middle = 0; //中间位置
int low = 0; //左边
int pow = elements; //右边
while(true){
middle = (pow + low) / 2;
if(arr[middle] == value){
return middle;
}else if(low > pow){
return -1;
}else{
if(arr[middle] > value){
pow = middle - 1;
}else{
low = middle + 1;
}
}
}
}
/*
* 根据索引查找数据
*/
public long searchByIndex(int index){
if(index < 0 || index >= elements){
throw new ArrayIndexOutOfBoundsException();
}else{
return arr[index];
}
}
/*
* 根据索引删除数据
*/
public void delete(int index){
if(index < 0 || index >= elements){
throw new ArrayIndexOutOfBoundsException();
}else{
for(int i = index;i < elements; i++){
arr[index] = arr[index + 1];
}
elements--;
}
}
/*
* 根据索引更新数据
*/
public void update(int index,int newvalue){
if(index < 0 || index >= elements){
throw new ArrayIndexOutOfBoundsException();
}else{
for(int i = index;i < elements; i++){
arr[index] = newvalue;
}
}
}
}