线性表(数组、链表)-ArrayList与LinkedList的自定义java实现

一、链表和数组

在这里插入图片描述
图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 );
      
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值