ArrayList详解

 

1.2.1、ArrayList

  1. 基于数组实现

  2. 动态扩容

    成员变量:

        //序列化标识   
         private static final long serialVersionUID = 8683452581122892189L;
     ​
         //默认的初始容量
         private static final int DEFAULT_CAPACITY = 10;
     ​
         //空_元素数据
         private static final Object[] EMPTY_ELEMENTDATA = {};
     ​
         //默认容量空_元素数据
         private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
     ​
         //用来存储ArrayList元素的数组
         transient Object[] elementData; // non-private to simplify nested class access
     ​
         //列表大小
         private int size;

    构造方法:

	/*
		*  用int类型的数据作为参数,实例化ArrayList
		*		如果参数大于0,则elementData是一个长度为10的数组,
		*		如果等于0,elementData就是一个空数组
		*/
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
   //不传参数的话,这个elementData就是一个空数组;
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
   //如果传的是一个Collection的集合,elementData就等于Collection转数组的值;
	//Arrays.copyOf()
    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

动态扩容

	//添加一个元素,调用ensureCapacityInternal()
		public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
		//往数组的第n个位置添加元素
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
		//计算属性
		//首先调用calculateCapacity() --->返回size++,或者DEFAULT_CAPACITY。
		//其次调用ensureExplicitCapacity() --->
    private void ensureCapacityInternal(int minCapacity) {
          ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
      }
		//计算容量,如果elementData是空数组,则在DEFAULT_CAPACITY与minCapacity取最大值;
		//如果elementData不是空,则直接返回minCapacity
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }

  

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
	
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
		//数组动态扩容的核心方法
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
     private static int hugeCapacity(int minCapacity) {
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
        }

当前数组是由默认构造方法生成的空数组并且第一次添加数据。此时minCapacity等于默认的容量(10)那么根据下面逻辑可以看到最后数组的容量会从0扩容成10。而后的数组扩容才是按照当前容量的1.5倍进行扩容; 当前数组是由自定义初始容量构造方法创建并且指定初始容量为0。此时minCapacity等于1那么根据下面逻辑可以看到最后数组的容量会从0变成1。这边可以看到一个严重的问题,一旦我们执行了初始容量为0,那么根据下面的算法前四次扩容每次都 +1,在第5次添加数据进行扩容的时候才是按照当前容量的1.5倍进行扩容。 当扩容量(newCapacity)大于ArrayList数组定义的最大值后会调用hugeCapacity来进行判断。如果minCapacity已经大于Integer的最大值(溢出为负数)那么抛出OutOfMemoryError(内存溢出)否则的话根据与MAX_ARRAY_SIZE的比较情况确定是返回Integer最大值还是MAX_ARRAY_SIZE。这边也可以看到ArrayList允许的最大容量就是Integer的最大值(-2的31次方~2的31次方减1)。】

判断是否包含contains

 public boolean contains(Object o) {
           return indexOf(o) >= 0;
       }
     public int indexOf(Object o) {
         if (o == null) {
             for (int i = 0; i < size; i++)
                 if (elementData[i]==null)
                     return i;
         } else {
             for (int i = 0; i < size; i++)
                 if (o.equals(elementData[i]))
                     return i;
         }
         return -1;
     }

总结:

可以看到上述contains 代码,实际上是调用了 indexOf 方法,如果返回值大于0,则返回true,说明集合中含有该元素,如果返回 值小于0,则返回 false,说明集合中不含有该元素。

删除

  public E remove(int index) {
         rangeCheck(index);
 ​
         modCount++;
         E oldValue = elementData(index);
 ​
         int numMoved = size - index - 1;
         if (numMoved > 0)
             System.arraycopy(elementData, index+1, elementData, index,
                              numMoved);
         elementData[--size] = null; // clear to let GC do its work
 ​
         return oldValue;
     }
 ​
     /**
      * Removes the first occurrence of the specified element from this list,
      * if it is present.  If the list does not contain the element, it is
      * unchanged.  More formally, removes the element with the lowest index
      * <tt>i</tt> such that
      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
      * (if such an element exists).  Returns <tt>true</tt> if this list
      * contained the specified element (or equivalently, if this list
      * changed as a result of the call).
      *
      * @param o element to be removed from this list, if present
      * @return <tt>true</tt> if this list contained the specified element
      */
     public boolean remove(Object o) {
         if (o == null) {
             for (int index = 0; index < size; index++)
                 if (elementData[index] == null) {
                     fastRemove(index);
                     return true;
                 }
         } else {
             for (int index = 0; index < size; index++)
                 if (o.equals(elementData[index])) {
                     fastRemove(index);
                     return true;
                 }
         }
         return false;
     }
 ​
     /*
      * Private remove method that skips bounds checking and does not
      * return the value removed.
      */
     private void fastRemove(int index) {
         modCount++;
         int numMoved = size - index - 1;
         if (numMoved > 0)
             System.arraycopy(elementData, index+1, elementData, index,
                              numMoved);
         elementData[--size] = null; // clear to let GC do its work
     }
 ​
     //清空数组,
     public void clear() {
         modCount++;
         for (int i = 0; i < size; i++)
             elementData[i] = null;
         size = 0;
     }
 

总结:

fastRemove():*把数组中后面的覆盖前面的,然后size减一

Clear():方法中将数组元素清空设置为null,即清除了对所有元素的引用,那么系统在gc的时候会将所有的元素清除,释放元素所占用的内存空间。

修改

  public E get(int index) {
         rangeCheck(index);
 ​
         return elementData(index);
     }
     public E set(int index, E element) {
         rangeCheck(index);
         E oldValue = elementData(index);
         elementData[index] = element;
         return oldValue;
     }

总结:

get():获取ArrayList下标的值

set(): 修改ArrayList下标对应的值

取子列表

      public List<E> subList(int fromIndex, int toIndex) {
             subListRangeCheck(fromIndex, toIndex, size);
             return new SubList(this, 0, fromIndex, toIndex);
         }
      SubList(AbstractList<E> parent,
                     int offset, int fromIndex, int toIndex) {
                 this.parent = parent;
                 this.parentOffset = fromIndex;
                 this.offset = offset + fromIndex;
                 this.size = toIndex - fromIndex;
                 this.modCount = ArrayList.this.modCount;
             }

实战:

1.约瑟夫环问题

 package com.boot.security.server.utils.test;
 ​
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Scanner;
 ​
 public class Joseph {
     public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);
         System.out.println("总人数:");
         int i = scanner.nextInt();
         System.out.println("数到第几位淘汰:");
         int n = scanner.nextInt();
         getJoseph(i,n);
     }
     public static void getJoseph(int size,int n){
         List<Character> list = new ArrayList<Character>();
         for (int i=0;i<size;i++){
             list.add((char) ('A'+i));
         }
         int i = 0; //计数起始位置
         while (list.size()>1) //多于一个对象时循环
         {
             i = (i+n-1) % list.size();
             System.out.print("删除"+list.remove(i).toString()+",");
             System.out.println(list.toString());
         }
         System.out.println("被赦免者是"+list.get(0).toString());
     }
 }
 ​

 

 

uploading.4e448015.gif转存失败重新上传取消uploading.4e448015.gif正在上传…重新上传取消uploading.4e448015.gif正在上传…重新上传取消uploading.4e448015.gif正在上传…重新上传取消uploading.4e448015.gif正在上传…重新上传取消uploading.4e448015.gif正在上传…重新上传取消

2.单列表查重 

package com.boot.security.server.utils.test;
 ​
 import io.swagger.models.auth.In;
 ​
 import java.util.*;
 ​
 public class SingleListDuplicate {
     public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         List list = new ArrayList();
         System.out.println("数组总长度:");
         int number = sc.nextInt();
 ​
         for (int i=0;i<number;i++){
             System.out.println("第"+(i+1)+"个元素");
             int num = sc.nextInt();
             list.add(num);
         }
         Dup(list);
         getCount(list);
     }
     /*去重*/
     public static void Dup(List list){
         Set set = new HashSet(list);
         System.out.println(set);
         System.out.println("----------------------------");
     }
     /*
     * 给定一个列表,给每个元素计数
     * */
     public static void getCount(List list){
         Map map = new HashMap<Integer,Object>();
         for (int i=0;i<list.size();i++){
             int frequency = Collections.frequency(list, list.get(i));
             map.put(list.get(i),frequency);
         }
         System.out.println(map);
     }
 }
 

 

 

uploading.4e448015.gif转存失败重新上传取消uploading.4e448015.gif正在上传…重新上传取消uploading.4e448015.gif正在上传…重新上传取消uploading.4e448015.gif正在上传…重新上传取消uploading.4e448015.gif正在上传…重新上传取消uploading.4e448015.gif正在上传…重新上传取消

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值