首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >java封装数组类

java封装数组类

作者头像
用户7886150
修改于 2020-12-04 17:17:50
修改于 2020-12-04 17:17:50
1.4K0
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: 用Java封装

学习数据结构,自己实现了一些数组的基本操作,里面可能会有错误,还望指正

 对数组的封装操作,类似于线性表中的顺序存储

 /**  

* @author NeoSong

* @date Oct 8, 2017 

* 5:44:10 PM

* program OF information: 1.自定义类MyArray来封装数组类

*                           2.定义操作数组类的方法              

*/                      

public class MyArray

     {

    private T[] arr;//定义数组,默认初始值为null

    private int last;//定义数组长度,默认初始化值为0

    private int maxsize;//定义数组长度的最大值

    //构造方法初始化变量

    public MyArray(){

        arr=(T[])new Object[50];//定义长度为50

    }

    //重载构造方法,maxsize为数组容量

    public MyArray(int maxsize){

        this.maxsize=maxsize;

        arr=(T[])new Object[maxsize];

    }

    //定义以下基本操作用来操作数组

    /*

     *  判断数组是否为空

     */

    public boolean isEmpty(){

        return last==0;

    }

    /*

     * 判断数组是否为满

     */

    public boolean isFull(){

        return last==maxsize;

    }

    /*

     * 求数组长度

     */

    public int count(){

        return last;

    }

    /*

     * 1.附加操作

     */

    public void attend(T ele){

        if(isFull()){

            throw new RuntimeException("数组已经满了");

        }

        arr[last++]=ele;//先赋值,后自增

    }

    /*

     * 2.显示数据

     */

    public void display(){

        System.out.print("[");

//        for(long ele : arr)

//            System.out.print(ele+" ");

        for(int i=0;i

     count()){

            throw new RuntimeException("location is wrong");

        }

        if(isEmpty()){

            throw new RuntimeException("数组为空");

        }

        return arr[i-1];

    }

    /*

     * 5.插入操作

     */

    public void insert(int i,T ele){

        if(i<1||i>count()){

            throw new RuntimeException("location is wrong");

        }

        if(isFull()){

            throw new RuntimeException("数组已经满了");

        }

        for(int j=last;j>=i;j--){

            arr[j]=arr[j-1];

        }

        arr[i-1]=ele;

        last++;//插入之后,别忘了last自增

    }

    /*

     * 6.删除操作

     */

    public void delete(int i){

        if(i<1||i>count()){

            throw new RuntimeException("location is wrong");

        }

        if(isEmpty()){

            throw new RuntimeException("数组为空");

        }

        for(int j=i-1;j

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档