模仿ArrayList封装ArrayBox
封装类:
package cn.com;
/**
* Created with Intellij IDEA
*
* @author XYP
* @Date: 2021/04/12/10:07
* @Description
*/
public class ArrayBox<E> {
private static final int DEFAULT_CAPACITY = 10;
private int size = 0;
private Object[] elementData;
/**当初始化时不给定数组长度时*/
public ArrayBox(){
elementData = new Object[DEFAULT_CAPACITY];
}
/**初始化时给定数组的大小时*/
public ArrayBox(int capacity){
elementData = new Object[capacity];
}
/**检查数组的索引是否合法*/
private void rangeCheck(int index){
if (index < 0 || index >= size){
//抛出自定义异常
throw new BoxIndexOutOfBoundsException("Array index crossing.");
}
}
/**判断容量是否够用*/
private void ensureCapacityInternal(int minCapacity){
if (minCapacity > elementData.length){
this.grow(minCapacity);
}
}
/**容量不够时扩容的方法*/
private void grow(int minCapacity){
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity < minCapacity){
newCapacity = minCapacity;
}
elementData = this.copyOf(elementData,newCapacity);
}
/**容量扩大时将数组复制到新数组*/
private Object[] copyOf(Object[] oldArray,int newCapacity){
Object[] newArray = new Object[newCapacity];
for (int i = 0; i < oldArray.length; i++) {
newArray[i] = oldArray[i];
}
return newArray;
}
//方法区
/**添加元素的方法*/
public boolean add(E element){
this.ensureCapacityInternal(size+1);
elementData[size++] = element;
return true;
}
/**获取元素*/
public E get(int index){
this.rangeCheck(index);
return (E)elementData[index];
}
/**移除元素*/
public E remove(int index){
/**检验数组下标是否合法*/
this.rangeCheck(index);
/**执行到此处,说明该数组下标是合法的,根据数组下标获取对应的元素*/
E oldValue = (E) elementData[index];
/**从当前下标开始将数组元素依次替换*/
for (int i = index;i < size - 1;i++){
elementData[i] = elementData[i+1];
}
/**
* 1 2 3 4 5 6
* 1 2 4 5 6 (6)最后需要将数组的最后一个元素替换
* */
elementData[--size] = null;
return oldValue;
}
}
测试类:
/**
* Created with Intellij IDEA
*
* @author XYP
* @Date: 2021/04/12/10:00
* @Description
*/
public class Test {
public static void main(String[] args) {
ArrayBox arrayBox = new ArrayBox(6);
arrayBox.add(1);
arrayBox.add(2);
arrayBox.add(3);
arrayBox.add(4);
arrayBox.add(5);
arrayBox.add(6);
arrayBox.add(7);
System.out.println(arrayBox.get(0));
System.out.println("被移除的元素为: " + arrayBox.remove(2));
System.out.println(arrayBox.get(1));
}
}
输出效果: