public class DIYArrayList<T> implements Iterable<T> {
private T[] data; //存储元素数组
private int size; //存储的元素个数
public DIYArrayList(){
this(10);
}
public DIYArrayList(int capacity){ //容量
if (capacity < 0){
try {
throw new IllegalAccessException("参数异常");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
data = (T[]) new Object[capacity];
this.size = 0;
}
//集合是否满
public boolean isFull(){
return this.size == this.data.length;
}
//扩容
public void grow(){
int newLength = size + size >> 1; //扩大1.5倍
data = Arrays.copyOf(data,newLength);
}
//范围判断
private boolean checkRange(int index){
if (index < 0 || index >= this.size){
throw new IndexOutOfBoundsException();
}
return true;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < this.size; i++) {
buffer.append(data[i]+" ");
}
return buffer.toString();
}
//增加
public boolean add(T e){
if (isFull()){
grow();
}
data[size++] = e;
return true;
}
//获取元素
public T get(int index){
checkRange(index);
return data[index];
}
//删除元素
public T remove(int index){
checkRange(index);
T num = data[index];
int mov = size-index-1;
System.arraycopy(data,index+1,data,index,mov);
data[--size] = null;
return num;
}
//删除
public boolean remove (T e){
if (e == null){
for (int i = 0; i < this.size; i++) {
if (data[i] == null){
int mov = size-i-1;
System.arraycopy(data,i+1,data,1,mov);
data[--size] = null;
return true;
}
}
}else {
for (int i = 0; i < this.size; i++) {
if (e.equals(data[i])){
int mov = size-i-1;
System.arraycopy(data,i+1,data,1,mov);
data[--size] = null;
return true;
}
}
}
return false;
}
@Override
public Iterator<T> iterator() {
return new Itr();
}
//实现迭代器
class Itr implements Iterator<T>{
private int afterIndex; //下一个位置
private int beforeIndex = -1; //前一个位置
@Override
public boolean hasNext() {
return afterIndex != size;
}
@Override
public T next() {
int i = afterIndex;
afterIndex += 1;
if (i > size){
throw new IndexOutOfBoundsException("越界异常");
}
T num = data[i];
beforeIndex = i;
return num;
}
@Override
public void remove() {
DIYArrayList.this.remove(beforeIndex);
afterIndex = beforeIndex;
beforeIndex = -1;
}
}
public static void main(String[] args) {
DIYArrayList<Integer> arrayList = new DIYArrayList<>();
arrayList.add(12);
arrayList.add(34);
arrayList.add(56);
arrayList.add(34);
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()) {
Integer value = iterator.next();
System.out.print(value+" ");
}
System.out.println();
iterator.remove();
System.out.println(arrayList);
}
}
运行结果:
注意:
要自定义迭代器类,类要具有iterator方法,需要实现iterable接口
自定义迭代器类需要实现 Iterator接口