一、链表和数组
图2解释的为单链表
应用:List:
- ArrayList:底层实现是数组,查询快,增删慢
- LinkedList:底层实现是双链表链表,查询慢,增删快
二、自定义类实现ArrayList与LinkedList
1、MyArrayList的实现(java代码)
public class MyArrayList<AnyType> implements Iterable<AnyType> {
//默认大小
private static final int DEFAULT_CAPACITY = 10;
//底层用数组实现,因为可以存放任何类型,所以使用泛型
private AnyType[] theItems;
//实际存放的元素个数
private int theSize;
//初始化
public MyArrayList( ){
doClear( );
}
//返回的实际元素个数
public int size( ){
return theSize;
}
//判断是否为空
public boolean isEmpty( ){
return size( ) == 0;
}
//返回指定索引位置的元素
public AnyType get( int idx ){
if( idx < 0 || idx >= size( ) )
throw new ArrayIndexOutOfBoundsException( "Index " + idx + "; size " + size( ) );
return theItems[ idx ];
}
//改变已有元素的值
public AnyType set( int idx, AnyType newVal ){
if( idx < 0 || idx >= size( ) )
throw new ArrayIndexOutOfBoundsException( "Index " + idx + "; size " + size( ) );
AnyType old = theItems[ idx ];
theItems[ idx ] = newVal;
return old;
}
//动态扩容
public void ensureCapacity( int newCapacity ){
if( newCapacity < theSize )
return;
AnyType [ ] old = theItems;
//因为创建泛型类型的数组是非法的,所以先创建一个Object类型的数组然后再强转成泛型类型的数组
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 idx, AnyType x