一、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/zh-tw/n/219930.html