您的位置:首页 > 其它

ArrayList类的实现

2018-01-27 16:12 99 查看
首先来说明实现细节:

MyArrayList将保持基础数组,数组的容量,以及存储在MyArrayList中的当前项数。

MyArrayList将提供一种机制来改变基础数组的容量,通过获得一个新的数组,并将老数组拷贝到新数组中来改变数组容量。

MyArrayList将提供get、set的实现

MyArrayList将提供基本的例程,如size、isEmpty和clear,以及remove和add的两个版本,如果数组的大小和容量相同,将增加容量。
MyArrayList将提供一个实现Iterator接口的类。

import java.util.Iterator;

public class MyArrayList<T> implements Iterable<T>{
private static final int DEFAULT_CAPACITY = 10;//初始容量
private int theSize;//大小
private T [] theItems;

public MyArrayList(){
doClear();
}

public void clear(){
doClear();
}

public int size(){
return theSize;
}

public void doClear(){
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}

public boolean isEmpty(){
return size() == 0;
}

public T get(int idx){
if(idx < 0|| idx >= size())//参数非法
throw new ArrayIndexOutOfBoundsException();
return theItems[idx];
}

public T set(int idx,T newVal){
if(idx < 0 || idx >= size())//参数非法
throw new ArrayIndexOutOfBoundsException();
T old = theItems[idx];
theItems[idx] = newVal;
return old;
}

public void ensureCapacity(int newCapacity){//保证容量
if(newCapacity < DEFAULT_CAPACITY){
return;
}
T [] old = theItems;
theItems = (T []) new Object[newCapacity];
for(int i = 0;i < size();i ++){
theItems[i] = old[i];
}
}

public boolean add(T x){
add(size(),x);
return true;
}

public void add(int idx,T x){
if(theItems.length == size()){//扩容
ensureCapacity(2*size()+1);
}
for(int i = theSize;i > idx;i --){//后移
theItems[i] = theItems[i-1];
}
theItems[idx] = x;
theSize++;
}

public T remove(int idx){
if(idx < 0 || idx >= size()){
throw new ArrayIndexOutOfBoundsException();
}
T removedItem = theItems[idx];
for(int i = idx;i < size()-1;i++){
theItems[i] = theItems[i+1];
}
theSize--;
return removedItem;
}

@Override
public Iterator<T> iterator() {//返回迭代器
return new ArrayListIterator();
}

private class ArrayListIterator<T> implements Iterator<T> {//实现迭代器
private int current = 0;
public boolean hasNext(){
return current < size();
}

public T next(){
if(!hasNext()){
throw new java.util.NoSuchElementException();
}
return (T) theItems[current++];
}
public void remove(){
MyArrayList.this.remove(--current);
}
}
}


下面是实际测试的代码:

MyArrayList<Integer> myList = new MyArrayList<Integer>();
System.out.println("空吗?"+myList.isEmpty());
for(int i = 0;i < 15;i ++){
myList.add(i);
}
System.out.println("大小:"+myList.size());
System.out.println("空吗?"+myList.isEmpty());
System.out.println("移除倒数第二个元素:"+myList.remove(13));
System.out.println("使用迭代器:");
Iterator iterator = myList.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+" ");
iterator.remove();
}
System.out.println("\n清空后大小:"+myList.size());测试结果:
空吗?true
大小:15
空吗?false
移除倒数第二个元素:13
使用迭代器:
0 1 2 3 4 5 6 7 8 9 10 11 12 14
清空后大小:0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: