线性表之顺序表(java实现)

public class SequenceList {
        //默认的顺序表的最大长度
        private final int defaultSize = 10;
        //最大长度
        private int maxSize;
        //当前长度
        private int size;
        //对象数组
        private Object[] listArray;


        public SequenceList() {
            init(defaultSize);
        }

        public SequenceList(int size) {
            init(size);
        }

        //顺序表的初始化方法
        private void init(int size) {
            maxSize = size;
            this.size = 0;
            listArray = new Object[size];
        }


        public void delete(int index) throws Exception {
            // TODO Auto-generated method stub
            if (isEmpty()) {
                throw new Exception("顺序表为空,无法删除!");
            }
            if (index < 0 || index > size - 1) {
                throw new Exception("参数错误!");
            }
            //移动元素
            for (int j = index; j < size - 1; j++) {
                listArray[j] = listArray[j + 1];
            }
            size--;
        }


        public Object get(int index) throws Exception {
            // TODO Auto-generated method stub
            if (index < 0 || index >= size) {
                throw new Exception("参数错误!");
            }
            return listArray[index];
        }


        public void insert(int index, Object obj) throws Exception {
            // TODO Auto-generated method stub
            //如果当前线性表已满,那就不允许插入数据
            if (size == maxSize) {
                throw new Exception("顺序表已满,无法插入!");
            }
            //插入位置编号是否合法
            if (index < 0 || index > size) {
                throw new Exception("参数错误!");
            }
            //移动元素
            for (int j = size - 1; j >= index; j--) {
                listArray[j + 1] = listArray[j];
            }

            listArray[index] = obj;  //不管当前线性表的size是否为零,这句话都能正常执行,即都能正常插入
            size++;

        }


        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return size == 0;
        }


        public int size() {
            // TODO Auto-generated method stub
            return size;
        }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值