public class SuperArray { //封装一个数组,想要什么都可以存,使用顶级父类Integer private Integer[] array; //数组长度 private int size; //数组当前的容量 private int capacity; //构造器初始化 public SuperArray(){ this(10); //默认长度10 this.capacity = 10; } //自定义长度初始化 public SuperArray(int capacity){ this.array = new Integer[capacity]; this.capacity = capacity; } //添加数据,默认尾插 public boolean add(Integer data){ //确保容量足够,如果容量不够就扩容 ensureCapacity(size + 1); array[size++] = data; return true; } //指定下标添加数据 public void add(int index,Integer data){ ensureCapacity(size + 1); //index以后的数据统一向后移动,空出位置 System.arraycopy(array,index,array,index+1,size-index); array[index] = data; } //删除最后一个 public Integer remove(){ if(size > 0){ return array[--size]; } return null; } //按照下标删除 public Integer remove(int index){ //检测下标是否越界,后面有具体实现 boolean flag = rangeCheck(index); if(flag){ Integer res = array[index]; System.arraycopy(array,index+1,array,index,size-index); size--; return res; } return null; } //修改数据 public boolean set(int index,Integer data){ //检测下标是否越界 boolean flag = rangeCheck(index); if (false){ array[index] = data; return true; } return false; } //根据下标查询数据 public Integer get(int index){ boolean flag = rangeCheck(index); if(flag){ return array[index]; } return null; } //查询当前有多少数据 public int size(){ return this.size; } //检查下标是否越界 private boolean rangeCheck(int index){ //只要有一个不满足就返回false return index <= size -1 && index >= 0; } //扩容方法 private void ensureCapacity(int neeedCapacity){ // System.out.println(neeedCapacity + "---" + capacity); if(neeedCapacity > capacity){ //如果容量不足扩容1.5倍 capacity = capacity+ (capacity >> 1); } } public static void main(String[] args) { SuperArray superArray = new SuperArray(); superArray.add(1); superArray.add(2); superArray.add(1); superArray.add(3); superArray.add(4); superArray.add(6); superArray.add(5); superArray.add(7); // for (int i = 0;i < superArray.size();i++) { // System.out.println(superArray.get(i)); // } System.out.println("---"+superArray.size()); superArray.add(3,100); // superArray.remove(); for (int i = 0;i < superArray.size();i++) { System.out.println(superArray.get(i)); } } }