本文以面向对象编程思想的角度来理解和使用数组,分为两个部分:
1.使用自定义类来封装数组;
public class MyArray {
private int[] arr;
//数组的有效长度(数组中实际存储元素的个数)
private int cloum;
public MyArray() {
arr=new int[50];
}
public MyArray(int cloum) {
arr=new int[cloum];
}
//插入
public void insert(int insertKey){
arr[cloum]=insertKey;
cloum++;
}
//显示
public void display(){
for (int i=0;i<cloum;i++){
System.out.print(arr[i]+" ");
}
}
//查找
public int search(int searchKey){
int k;
for (k=0;k<cloum;k++){
if(arr[k]==searchKey){
break;
}
}
System.out.println("");
if(k==cloum){
System.out.println("要查找的"+searchKey+"在数组中不存在!");
return -1;
}else{
System.out.println("要查找的"+searchKey+"在数组中的下标为"+k);
return k;
}
}
//删除
public void delete(int deleteKey){
//删除首先需要完成查找,如果把search方法改为静态方法,arr[]成为静态数组,不方便启动测试类恢复,在此直接copy查找方法的代码
int index;
for (index=0;index<cloum;index++){
if(arr[index]==deleteKey){
break;
}
}
if(index==cloum){
System.out.println("要删除的数"+deleteKey+"在数组中不存在,删除失败!");
}else{
//从index位置开始,数组之后的元素全部前移一位(注意数组越界!)
for(int i=index;i<cloum-1;i++){
arr[i]=arr[i+1];
}
cloum--;
}
}
//修改
public void update(int oldKey,int newKey){
int j=search(oldKey);
if(j==-1){
System.out.println("要修改的数"+oldKey+"在数组中不存在,无法修改");
}else{
arr[j]=newKey;
}
}
}
2.使用测试类来实现对数组的插入、显示、查找、删除和修改操作。
public class arrTest {
public static void main(String[] args) {
MyArray arr=new MyArray();
arr.insert(5);
arr.insert(15);
arr.insert(25);
arr.insert(35);
arr.display();
arr.search(20);
//arr.delete(25);
arr.display();
arr.update(35, 45);
arr.display();
}
}