Google guava
Guava是对Java API的补充,对Java开发中常用功能进行更优雅的实现,使得编码更加轻松,代码容易理解。Guava使用了多种设计模式,同时经过了很多测试,得到了越来越多开发团队的青睐。Java最新版本的API采纳了Guava的部分功能,但依旧无法替代。
特点
- 高效设计良好的API,被Google的开发者设计,实现和使用
- 遵循高效的java语法实践
- 使代码更刻度,简洁,简单
- 节约时间,资源,提高生产力 Guava工程包含了若干被Google的 Java项目广泛依赖的核心库
核心库例如:
- 集合 [collections]
- 缓存 [caching]
- 原生类型支持 [primitives support]
- 并发库 [concurrency libraries]
- 通用注解 [common annotations]
- 字符串处理 [string processing]
- I/O 等等。
github地址
https://github.com/google/guava
https://github.com/google/guava
使用
依赖引入
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
</dependencies>
Guava 集合工具类
Lists
官网文档:
Lists (Guava: Google Core Libraries for Java 27.0.1-jre API)
https://guava.dev/releases/27.0.1-jre/api/docs/com/google/common/collect/Lists.html对应于List集合接口, 在com.google.common.collect包下
Lists 接口的声明如下:
@GwtCompatible(emulated=true)
public final class Lists
extends Object
Lists 类主要提供了对List类的子类构造以及操作的静态方法。在Lists类中支持构造 ArrayList、LinkedList 以及 newCopyOnWriteArrayList 对象的方法。其中提供了以下构造ArrayList的函数:下面四个构造一个 ArrayList 对象,但是不显式的给出申请空间的大小:
newArrayList()
newArrayList(E... elements)
newArrayList(Iterable<? extends E> elements)
newArrayList(Iterator<? extends E> elements)
测试
ArrayList<Object> objects = Lists.newArrayList();
objects.add("张三");
objects.add(20);
System.out.println("--- newArrayList test ---");
System.out.println(objects);
System.out.println("--- newArrayList test ---");
ArrayList<Object> objects1 = Lists.newArrayList(objects);
System.out.println(objects1);
System.out.println("--- newArrayList test ---");
ArrayList<String> strings = Lists.newArrayList("张三", "北京市海淀区");
System.out.println(strings);

以下两个函数在构造 ArrayList 对象的时候给出了需要分配空间的大小:
newArrayListWithCapacity(int initialArraySize)
newArrayListWithExpectedSize(int estimatedSize)
//如果你事先知道元素的个数,可以用 newArrayListWithCapacity 函数;如果你不能确定元素的个数,可以用newArrayListWithExpectedSize函数
//这个方法就是直接返回一个10的数组。
ArrayList<Object> objects = Lists.newArrayListWithCapacity(10);
objects.add("123");
System.out.println(objects);
ArrayList<Object> objects1 = Lists.newArrayListWithExpectedSize(10);
objects1.add("123");
System.out.println(objects1);


最低0.47元/天 解锁文章
1595

被折叠的 条评论
为什么被折叠?



