自定义arraylist

public class MyArrayList
{
      private Object [] elementData;
      private int size;


      public MyArrayList ( int initCapacity )
      {
            if ( initCapacity < 0 )
                  throw new RuntimeException("初始化长度必须大于0");
            elementData = new Object [initCapacity];
      }


      public MyArrayList ()
      {
            this(10);
      }


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


      public int size ()
      {
            return size;
      }


      public void add ( Object obj,int index )
      {
            ensureCapacity(size + 1);
            RangeCheck(index) ;
            
            int numMoved = size - index ;//要移动的个数


            if ( numMoved > 0 )
                  System.arraycopy(elementData, index , elementData, index+1, numMoved);
            
            elementData [index] = obj; 
            size++;
            
      }
      
      public void add ( Object obj )
      {
            ensureCapacity(size + 1);
            elementData [size++] = obj;
      }


      public Object get ( int index )
      {
            RangeCheck(index);
            return elementData [index];
      }


      public Object remove ( int index )
      {
            RangeCheck(index);


            Object oldObj = elementData [index];


            int numMoved = size - index - 1;//要移动的个数


            if ( numMoved > 0 )
                  System.arraycopy(elementData, index + 1, elementData, index, numMoved);
            elementData [--size] = null;
            return oldObj;
      }


      public Object remove ( Object obj )
      {
            for ( int i = 0; i < size; i++ )
            {
                  if ( elementData [i].equals(obj) )
                  {
                        return remove(i);
                  }
            }
            return null;
      }


      private void RangeCheck ( int index )
      {
            if ( index >= size )
            {
                  throw new RuntimeException("访问数据小标越界");
            }


      }


      private void ensureCapacity ( int minCapacity )
      {
            int oldCapacity = elementData.length;
            if ( minCapacity > oldCapacity )
            {
                  int newCapacity = ( oldCapacity * 3 ) / 2 + 1;
                  if ( newCapacity < minCapacity )
                        newCapacity = minCapacity;
                  //  elementData = Arrays.copyOf(elementData, newCapacity);
                  Object [] newElements = new Object [newCapacity];
                  System.arraycopy(elementData, 0, newElements, 0, oldCapacity);
                  elementData = newElements;
            }


      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值