一、of函数概述
of函数是Guava库中的一个静态函数,其核心作用是创建一个不可变的、包含若干元素的列表。它接受0~多个元素作为参数,返回一个ImmutableList类型的实例。
/**
* Returns an immutable list containing zero or more elements.
*/
public static <E> ImmutableList<E> of() {
return ImmutableList.<E>of();
}
/**
* Returns an immutable list containing exactly one element.
*/
public static <E> ImmutableList<E> of(E element) {
return ImmutableList.<E>of(element);
}
/**
* Returns an immutable list containing exactly the given elements, in order.
*
* @throws NullPointerException if any of the elements are null
*/
public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5,
E e6, E e7, E e8, E e9, E e10, E... others) {
return ImmutableList.<E>of(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, others);
}
以上是ImmutableList类中of方法的声明与实现。虽然从逻辑上说这三个方法应该是合并成同一个方法的,只是参数个数不同而已。但是Guava设计者的思考是,根据Java的重载机制,如果使用同一个方法,那么在调用时必须要显式指定参数类型,这会让代码变得麻烦。所以他们设计了三个带有不同参数的of方法。
二、使用示例
我们通过下面的示例代码来演示如何使用ImmutableList中的of方法:
import com.google.common.collect.ImmutableList;
public class ImmutableListDemo {
public static void main(String[] args) {
// 创建空列表
ImmutableList<Integer> list1 = ImmutableList.of();
// 创建单元素列表
ImmutableList<String> list2 = ImmutableList.of("hello");
// 创建多元素列表
ImmutableList<String> list3 = ImmutableList.of("just", "do", "it");
System.out.println(list1); // []
System.out.println(list2); // [hello]
System.out.println(list3); // [just, do, it]
}
}
以上程序会输出:
[]
[hello]
[just, do, it]
从这个示例中可以发现,使用of方法创建ImmutableList非常简便,甚至一行代码都不需要。
三、of函数优势
1)不可变
ImmutableList是一个不可变的列表,这意味着一旦创建之后,就无法进行修改。这种特性保证了程序的健壮性,防止在多线程环境下发生数据竞争。
2)类型安全
of方法是一个泛型方法,调用者必须明确地指定元素类型。这种类型安全能够避免由于类型错误引发的运行时异常。
3)可读性
使用of方法能让代码更为简洁易懂,增强了代码的可读性,降低了维护成本。
四、immutableList.of函数的局限性
虽然of方法非常方便,但是它存在以下几个局限性:
1)元素个数限制
of方法最多只能接受10个元素,如果有更多的元素,就必须使用另外一种方式来创建ImmutableList。
2)参数不能为null
当传入的参数中存在null值时,会抛出NullPointerException异常。这种行为可能会让程序员感到意外和烦恼。
3)只能用于加入元素的初始值设定
of方法只适用于列表初始值的设定,无法用于动态的增加元素(因为ImmutableList是不可变的)。如果需要动态地加入元素,必须使用ImmutableList.Builder类。
五、总结
ImmutableList是Guava库提供的一个常用类,它的of方法为程序员提供了一种简便的方式来创建不可变列表。虽然of方法便捷性非常高,但是它也存在各种限制和局限性,程序员在使用时必须特别注意。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/219930.html