实现了一个简单的ArrayList
- 这么看来,java.util.ArrayList 是对对象数组的封装,加上了一些方法,可以进行更多的操作。
- 但是要注意,经常要做插入、删除的操作,数组并不理想,开销比较昂贵。
- 数组的本质就是抽象数据类型—表(list)的一种实现方式
- 要访问特定元素,可以使用索引访问,时间复杂度为 O(1)。
- 要想在顺序表中插入或删除一个元素,都涉及到之后所有元素的移动,因此时间复杂度为 O(n)。
MyArrayList.java
package doppler.List;
public class MyArrayList<Type> implements Iterable<Type> {
private static final int DEFAULT_CAPACITY=10;
private int theSize;
private Type[] theItems;
public MyArrayList(){
clear();
}
public void clear(){
theSize=0;
ensureCapacity(DEFAULT_CAPACITY);
}
public int size(){
return theSize;
}
public boolean isEmpty(){
return size()==0;
}
public void trimToSize(){
ensureCapacity(size());
}
public Type get(int index){
if(index<0||index>=size()){
throw new ArrayIndexOutOfBoundsException();
}
return theItems[index];
}
public Type set(int index,Type newVal){
if (index<0||index>=size()) {
throw new ArrayIndexOutOfBoundsException();
}
Type old=theItems[index];
theItems[index]=newVal;
return old;
}
public void ensureCapacity(int newCapacity){
if(newCapacity<theSize){
return;
}
Type [] old=theItems;
theItems=(Type [])new Object[newCapacity];
for(int i=0;i<size();i++){
theItems[i]=old[i];
}
}
public boolean add(Type x){
add(size(),x);
return true;
}
public void add(int index, Type x){
if (theItems.length==size()) {
ensureCapacity(size() * 2 + 1);
}
for (int i = size(); i < index; i--) {
theItems[i]=theItems[i-1];
}
theItems[index]=x;
theSize++;
}
public Type remove(int index ){
Type removeItem=theItems[index];
for(int i=index;i<size()-1;i++){
theItems[i]=theItems[i+1];
}
theSize--;
return removeItem;
}
public java.util.Iterator<Type> iterator() {
return null;
}
private class ArrayListIterator implements java.util.Iterator<Type>{
private int current = 0;
public boolean hasNext() {
return current<size();
}
public Type next() {
return theItems[current++];
}
public void remove(){
MyArrayList.this.remove(--current);
}
}
}
MyArrayListDemo.java
package doppler.test;
import doppler.List.MyArrayList;
public class MyArrayListDemo {
public static void main(String[] args) {
Object instance=new Object();
MyArrayList<Object> myArrayList=new MyArrayList<>();
myArrayList.add(instance);
System.out.println(myArrayList.size()+" "+myArrayList.get(0).toString());
MyArrayListDemo demo=new MyArrayListDemo();
MyArrayListDemo demo2=new MyArrayListDemo();
MyArrayList myArrayList2=new MyArrayList<>();
myArrayList2.add(demo);
myArrayList2.add(demo2);
System.out.println(myArrayList2.size()+" "+myArrayList2.get(1).toString());
myArrayList.remove(0);
myArrayList2.clear();
System.out.println(myArrayList2.size());
myArrayList.ensureCapacity(17);
System.out.println(myArrayList.size());
}
@Override
public String toString() {
return "hello, this is a demo ";
}
}