Lists.newArrayList

来源:互联网 发布:淘宝店铺爆款神器软件 编辑:程序博客网 时间:2024/06/08 03:35

这个方法在google工具类中也有,源码内容如下

1
2
3
public static <E> ArrayList<E> newArrayList() {
    return new ArrayList();
}

内容是差不多的,唯一的好处就是可以少写泛型的部分。

但这个方法却有丰富的重载:

1
2
3
Lists.newArrayList(E... elements)
Lists.newArrayList(Iterable<? extends E> elements)
Lists.newArrayList(Iterator<? extends E> elements)

还有很多前缀扩展方法:

1
2
List<T> exactly = Lists.newArrayListWithCapacity(100);
List<T> approx = Lists.newArrayListWithExpectedSize(100);

使得函数名变得更有可读性,一眼就看出方法的作用,new ArrayList(100)的可读性就比较差了。


参考内容:

  1. http://stackoverflow.com/questions/9980915/lists-newarraylist-vs-new-arraylist

  2. https://github.com/google/guava/wiki/CollectionUtilitiesExplained#Static_constructors

原创粉丝点击