package ch01;
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 display(){
System.out.print("[");
for(int i=0;i<elements;i++){
System.out.print(arr[i]+" ");
}
System.out.print("]");
System.out.println();
}
//查找数据的方法,查找数据根据值来查找,返回值的下标
public int search(long value){
int i;
for(i=0;i<elements;i++){
if(arr[i] == value){
break;
}
}
if(i == elements){
return -1;
}else{
return i;
}
}
//查找数据,根据索引返回值
public long get(int index){
//判断数组是不是越界
if(index < 0 || index >= elements){
throw new ArrayIndexOutOfBoundsException("数组越界");
}else{
return arr[index];
}
}
//删除数据
public void delete(int index){
if(index >=elements || index < 0){
throw new ArrayIndexOutOfBoundsException("数组越界");
}else{
for(int i=index;i<elements;i++){
arr[index] = arr[index+1];
}
//数组的长度--
elements--;
}
}
//更新数据
public void change(int index,int newvalue){
if(index >= elements || index < 0) {
throw new ArrayIndexOutOfBoundsException();
} else {
arr[index] = newvalue;
}
}
}