栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

集合框架--3、ArrayList扩容

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

集合框架--3、ArrayList扩容

1. ArrayList() 会使用长度为零的数组 2. ArrayList(int initialCapacity) 会使用指定容量的数组 3. public ArrayList(Collection c) 会使用 c 的大小作为数组容量 4. add(Object o) 首次扩容为 10,再次扩容为上次容量的 1.5 倍 5. addAll(Collection c) 没有元素时,扩容为 Math.max(10, 实际元素个数),有元素时为 Math.max(原容量 1.5 倍, 实际元素个数)
扩容方式不是简单的*1.5倍
public  class  TestArrayList {      public  static  void  main(String[] args) {          System.out.println(arrayListGrowRule( 30 ));          // testAddAllGrowEmpty();          testAddAllGrowNotEmpty();      }      private  static  List arrayListGrowRule( int  n) {          List list =  new  ArrayList<>();          int  init =  0 ;          list.add(init);          if  (n >=  1 ) {              init =  10 ;              list.add(init);          }          for  ( int  i =  1 ; i < n; i++) {              init += (init) >>  1 ;              list.add(init);          }          return  list;      }      // addAll(Collection c) 没有元素时,扩容为 Math.max(10, 实际元素个数),      // 有元素时为 Math.max(原容量 1.5 倍, 实际元素个数)      private  static  void  testAddAllGrowEmpty() {          ArrayList list =  new  ArrayList<>();          // list.addAll(Arrays.asList(1, 2, 3));// 10          list.addAll(Arrays.asList( 1 ,  2 ,  3 ,  4 ,  5 ,  6 ,  7 ,  8 ,  9 ,  10 ,  11 )); // 11          System.out.println(length(list));      }      // addAll(Collection c) 没有元素时,扩容为 Math.max(10, 实际元素个数),      // 有元素时为 Math.max(原容量 1.5 倍, 实际元素个数)      private  static  void  testAddAllGrowNotEmpty() {          ArrayList list =  new  ArrayList<>();          for  ( int  i =  0 ; i <  10 ; i++) {              list.add(i);          } // list里面已经有10个元素          // list.addAll(Arrays.asList(1, 2, 3));// max(15,10)=15          list.addAll(Arrays.asList( 1 ,  2 ,  3 ,  4 ,  5 ,  6 )); // max(15,16)=16          System.out.println(length(list));      }      public  static  int  length(ArrayList list) {          try  {              Field field = ArrayList. class .getDeclaredField( "elementData" );              field.setAccessible( true );              return  ((Object[]) field.get(list)).length;          }  catch  (Exception e) {              e.printStackTrace();              return  0 ;          }      } }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/692295.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号