guava下Lists,newArrayListWithExpectedSize()和newArrayListWithCapacity()使用示例

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

源码:

public static <E> ArrayList<E> newArrayListWithCapacity(int initialArraySize) {
        CollectPreconditions.checkNonnegative(initialArraySize, "initialArraySize");
        return new ArrayList(initialArraySize);
    }
 public static <E> ArrayList<E> 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个数据时,这个容器才会进行扩容,优点:节约内存,节约时间,节约性能,

 

posted @ 2020-04-28 11:44  yorkd  阅读(3375)  评论(0编辑  收藏  举报