package com.original.algorithm.table;
import java.util.Iterator;
public class MyArrayList implements Iterable {
private static final int DEFAULT_SIZE = 10;
private int theSize; private AnyType[] theItems; public MyArrayList() { doClear(); } public void clear() { doClear(); } private void doClear() { theSize = 0; enSureCapacity(DEFAULT_SIZE); } public int size() { return theSize; } private void enSureCapacity(int capacity) { // 可加可不加校验 if (capacity < theSize) { return; } AnyType[] old = theItems; theItems = (AnyType[]) new Object[capacity]; for (int i = 0; i < size(); i++) { theItems[i] = old[i]; } } public AnyType get(int idx) { if (idx < 0 || idx >= theSize) { throw new IndexOutOfBoundsException(); } return theItems[idx]; } public AnyType set(int idx, AnyType x) { if (idx < 0 || idx >= theSize) { throw new IndexOutOfBoundsException(); } AnyType old = theItems[idx]; theItems[idx] = x; return old; } public void add(AnyType x) { add(size(), x); } private void add(int idx, AnyType x) { // 判断是否需要扩容 if (idx == size()) { enSureCapacity(size() * 2 + 1); } // 插入合适位置并移动数组 - 先移动数组 for (int i = size(); i > idx; i--) { theItems[i] = theItems[i - 1]; } theItems[idx] = x; theSize++; } public void remove(int idx) { // 删除 - 将需要删除的原始的前一位一直覆盖 for (int i = idx; i < size() - 11; i++) { theItems[i] = theItems[i + 1]; } theSize--; } @Override public Iterator<AnyType> iterator() { // 主要学习数据类型的实现方式 暂不理会 return null; }
}