可能在用到java中的集合时,许多人都会用ArrayList.这里我们自己写一个ArrayList类。
1、MyArrayList将保持基础数组,数组的容量,以及存储在MyArrayList中的当前项数。
2、MyArrayList将提供一种机制以改变基础数组的容量。通过获得一个新数组,将老数组拷贝到新数组中来改变数组的容量,允许虚拟机收回老数组
3、MyArrayList将提供get和set的实现
4、MyArrayList将提供基本的例程,如size、isEmpty、和clear,它们是典型的单行程序;还提供remove,以及两种不同版本的add。如果数组的大小和容量相同,那么这两个add例程将增加容量。
5、MyArrayList将提供一个实现Iterator接口的类。这个类将存储迭代序列中的下一项的下标。并提供next、hasNext、和remove等方法的实现。MyArrayList的迭代器方法直接返回实现Itrator接口的该类的新构造的实例。
package com.qianfeng.collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyArrayList<AnyType> implements Iterable<AnyType> {
private static final int DEFAULT_CAPACITY = 10; //创建集合默认大小
private int theSize; // 大小
private AnyType[] theItems;
/*
* 构造函数
*/
public MyArrayList() {
clear();
}
public void clear() {
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
// 返回集合大小
public int size() {
return this.theSize;
}
// 判断集合是否为空
public boolean isEmpty() {
return this.size() == 0;
}
// 扩充容量
public void trimTosize() {
ensureCapacity(size());
}
// 下标获取元素值
public AnyType get(int index) {
if (index >= size() || index < 0)
throw new ArrayIndexOutOfBoundsException();
return theItems[index];
}
// 修改元素值,并返回原来的值
public AnyType set(int index, AnyType newVal) {
if (index >= size() || index < 0)
throw new ArrayIndexOutOfBoundsException();
AnyType old = theItems[index];
theItems[index] = newVal;
return old;
}
@SuppressWarnings("unchecked")
public void ensureCapacity(int newCapacity) {
if (newCapacity < theSize)
return;
AnyType[] old = theItems;
theItems = (AnyType[]) new Object[newCapacity];
for (int i = 0; i < size(); i++) {
theItems[i] = old[i];
}
}
// 添加元素
public boolean add(AnyType x) {
add(size(), x);
return true;
}
// 利用下标添加元素
public void add(int index, AnyType x) {
if (theItems.length == size()) {
ensureCapacity(size() * 2 + 1);
}
for (int i = theSize; i > index; i--)
theItems[i] = theItems[i - 1];
theItems[index] = x;
theSize++;
}
//删除元素
public AnyType remove(int index){
AnyType removeItem = theItems[index];
for(int i = index; i < size()-1; i++){
theItems[i] = theItems[i+1];
}
theSize--;
return removeItem;
}
public Iterator<AnyType> iterator(){
return new ArrayListIterator<AnyType>(this);
}
//内部类,迭代器
private static class ArrayListIterator<AnyType> implements Iterator<AnyType>{
private MyArrayList<AnyType> theList;
public ArrayListIterator(MyArrayList<AnyType> list){
theList = list;
}
private int current = 0;
@Override
public boolean hasNext() {
return current < theList.size();
}
@Override
public AnyType next() {
if(!hasNext()){
throw new NoSuchElementException();
}
return theList.theItems[current++];
}
public void remove(){
theList.remove(--current);
}
}
}