(1)简单数组

数组是具有相同的数据类型且按一定次序排列的一组变量的集合体,构成一个数组的这些变量称为数组元素。
这里编写一个简单数组:


public class TestArray {
    private int[] arr;
    private int maxSize; //数组大小
    private int length;  //当前长度,即数组中有多少项

    /**
     * 
     * @Description:初始化数组
     * @param max 数组大小
     */
    public TestArray(int max){
        this.arr = new int[max];
        this.maxSize = max;
        this.length = 0;//当前数组中有0项
    }

    /**
     * 
     * Description:插入某个值
     * @return boolean
     */
    public boolean insert(int value){
        if(maxSize == length){//数组已满
            return false;
        }
        arr[length] = value;//将数据插入数组
        length ++;
        return true;        
    }

    /**
     * 
     * Description:删除某个值
     * @return boolean
     */
    public boolean delete(int value){
        int i;
        for(i=0; i<length; i++){//遍历比较得到下标
            if(arr[i] == value){
                break;
            }
        }
        if(i == length){
            return false;
        }
        if(length == maxSize){//如果数组已满
            for(int j=i; j<length-1; j++){
                arr[j] = arr[j+1];//将删除元素的后继依次前移
            }
        }
        else{//数组未满
            for(int j=i; j<length; j++){
                arr[j] = arr[j+1];
            }
        }
        length--;
        return true;
    }

    /**
     * 
     * Description:查找某个元素
     * @return boolean
     */
    public boolean find(int value){
        int i;
        for(i=0; i<length; i++){
            if(arr[i] == value){//存在返回真
                System.out.println("存在");
                return true;
            }
        }
        //不存在返回假
        System.out.println("不存在");
        return false;   
    }

    public void printArr(){//遍历整个数组
        for(int i=0 ;i<length; i++){
            System.out.print(arr[i]+" ");
        }
    }

    public static void main(String[] args) {
        TestArray arr = new TestArray(4);
        arr.insert(2);
        arr.insert(4);
        arr.insert(3);
        arr.insert(5);

        arr.delete(4);
        arr.find(1);
        arr.printArr();
    }
}

猜你喜欢

转载自blog.csdn.net/pianpiannia/article/details/76253137