ArrayList详解

来源:互联网 发布:知天下图片野战 编辑:程序博客网 时间:2024/06/04 20:04

ArrayList底层实现是对数组的操作,我们来看一下我自己写的ArrayList类

package com.org.List;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
 * ArrayList线性表实现
 */
public class MyArrayList<AnyType> implements Iterable<AnyType> {

//默认数组大小

private static final int DEFAULT_CAPACITY = 10;

//数组中存储数据大小

private int theSize;

//数组,存储数据

private AnyType[] theItems;

/**

* 初始化MyArrayList

*/

public MyArrayList(){

clear();

}

//增加数据

public boolean add(AnyType x){

add(size(),x);

return true;

}

//增加数据

public void add(int idx,AnyType x){

if(theItems.length == size())

ensureCapacity(size()*2+1);

for(int i=theSize;i>idx;i--)

theItems[i] = theItems[i-1];

theItems[idx] = x;

theSize++;

}


//删除数据

public AnyType remove(int idx){

AnyType removeItem = theItems[idx];

for(int i=idx;i<size()-1;i++)

theItems[i] = theItems[i+1];

theSize--;

return removeItem;

}

//更改数据

public AnyType set(int idx,AnyType newVal){

if(idx<0||idx>=size())

throw new ArrayIndexOutOfBoundsException();

AnyType old = theItems[idx];

theItems[idx] = newVal;

return old;

}

//查询数据

public AnyType get(int idx){

if(idx<0||idx>=size())

throw new ArrayIndexOutOfBoundsException();

return theItems[idx];

}

//防止数组越界,扩容

@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 int size(){

return theSize;

}

//判断数组是否为空

public boolean isEmpty(){

return size()==0;

}

//清除数据

public void clear(){

theSize=0;

ensureCapacity(DEFAULT_CAPACITY);

}

public Iterator<AnyType> iterator() {

return new ArrayListIterator();

}

private class ArrayListIterator implements Iterator<AnyType>{

private int current = 0;

public boolean hasNext() {

return current<size();

}

@Override

public AnyType next() {

if(!hasNext())

throw new NoSuchElementException();

return theItems[current++];

}

@Override

public void remove() {

MyArrayList.this.remove(--current);

}

}

}

从中可以看出,Arraylist对于get()和set()方法操作时间是常数,而对add()和remove()则花费线性时间

所以ArrayList对于get()跟set()数据效率高,而对于添加数据和删除数据其效率就比较低

在这里我们给ArrayList写了一个迭代器,但是通过增强的for循环时不能调用非迭代器实现的remove方法,否则出现

ConcurrentModificationException,即迭代器使用迭代器内部的remove。

举例说明:

public static void removeEvensVer2(List<Integer>lst){

for(Integer x:lst)

if(x%2 == 0)

lst.remove(x);

}

将出现异常

0 0
原创粉丝点击