package cn.thj.data_structures;
import java.util.Iterator;
public class MyArrayList<T> implements Iterable<T> {
// 定义默认的大小
private static final int DEFAULT_CAPACITY = 10;
private T[] Items;
private int size;
// 默认构造
public MyArrayList() {
clear();
};
// 清空集合
public void clear() {
size = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
/**
* 保持集合容量增长
*
* @param newCapacity
*/
public void ensureCapacity(int newCapacity) {
if (newCapacity < size) {
return;
}
T[] old = Items;
Items = (T[]) new Object[newCapacity];
for (int i = 0; i < size(); i++) {
Items[i] = old[i];
}
}
// 返回集合的大小
public int size() {
return size;
}
// 是集合的容量为集合的大小
public void trimToSize() {
ensureCapacity(size());
}
// 判断集合是否为空
public boolean isEmpty() {
return size() == 0;
}
// 检查集合的边界,判断是否越界
private void RangeCheck(int index) {
if (index >size || index < 0)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: "
+ size);
}
// 取指定位置的值
public T get(int index) {
RangeCheck(index);
return Items[index];
}
// 给指定位置设值
public T set(int index, T newVal) {
RangeCheck(index);
T old = Items[index];
Items[index] = newVal;
return Items[index];
}
// 添加元素,默认添加到末尾
public boolean add(T val) {
add(size(), val);
return true;
}
/**
* 根据指定位置添加数据
*
* @param index
* 添加的位置
* @param val
* 添加的值
*/
public void add(int index, T val) {
RangeCheck(index);
if (Items.length == size()) {
ensureCapacity(size() * 2 + 1);
}
for (int i = size; i > index; i--) {
Items[i] = Items[i - 1];
}
Items[index] = val;
size++;
}
/**
* 删除指定位置的元素
*
* @param index
* 删除的位置
* @return removeItem
* 返回被删除的元素
*/
public T remove(int index) {
RangeCheck(index);
T removeItem = Items[index];
for (int i = index; i < size; i++) {
Items[i] = Items[i + 1];
}
size--;
return removeItem;
}
public Iterator<T> iterator() {
return new ArrayListIterator();
}
/**
*实现迭代器,这里是用一个内部类来实现的
*/
private class ArrayListIterator implements java.util.Iterator<T> {
private int current = 0;
private boolean okToRemove = false;
public boolean hasNext() {
return current < size();
}
public T next() {
if (!hasNext())
throw new java.util.NoSuchElementException();
okToRemove = true;
return Items[current++];
}
public void remove() {
if (!okToRemove)
throw new IllegalStateException();
MyArrayList.this.remove(--current);
okToRemove = false;
}
}
}
数据结构之顺序表
最新推荐文章于 2022-10-14 22:38:53 发布