guava Lists下通过了两个创建指定容量的list方法,newArrayListWithExpectedSize,newArrayListWithCapacity。它们主要的区别如下:

https://www.cnblogs.com/yorkd/p/12793088.html

guava Lists下通过了两个创建指定容量的list方法,newArrayListWithExpectedSize,newArrayListWithCapacity。它们主要的区别如下:

源码:

public static ArrayList newArrayListWithCapacity(int initialArraySize) {
CollectPreconditions.checkNonnegative(initialArraySize, “initialArraySize”);
return new ArrayList(initialArraySize);
}
复制代码
public static ArrayList newArrayListWithExpectedSize(int estimatedSize) {
return new ArrayList(computeArrayListCapacity(estimatedSize));
}

@VisibleForTesting
static int computeArrayListCapacity(int arraySize) {
CollectPreconditions.checkNonnegative(arraySize, “arraySize”);
return Ints.saturatedCast(5L + (long)arraySize + (long)(arraySize / 10));
}
复制代码
通过方法**Size参数创建一个定容的集合。

1、如果你确定你的容器装多少个,不会改变,一般直接使用

newArrayListWithCapacity(),如果容器超过定义size,它会自动扩容,不用担心容量不够。扩容后,会将原来的数组复制到新的数组中,但扩容会带来一定的性能影响:包括开辟新空间,copy数据,耗时,耗性能

2、如果你的不确定你的容器多少个,但增幅不会太大,使用

newArrayListWithExpectedSize(),会直接创建一个指定size的容器,但它会通过一条公式计算来进行扩容 (

5L + (long)arraySize + (long)(arraySize / 10)
),例如,创建一个10个size的容器,那么 5+10 + (10/10) = 16,当容器添加第17个数据时,这个容器才会进行扩容,优点:节约内存,节约时间,节约性能,

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值