首页 > 文章列表 > Java 9中集合工厂方法的条件是什么?

Java 9中集合工厂方法的条件是什么?

367 2023-08-20

在Java 9中,工厂方法已被添加到Collections API中。我们可以使用它来创建不可修改的列表、集合映射对象,以减少代码行数。 List.of()、Set.of()、Map.of()Map.ofEntries()是提供方便的创建不可变的集合静态工厂方法

以下是集合工厂方法的条件

  • 它们在结构上是不可变的。
  • 它们不允许空元素或空键。
  • 如果所有元素都是可序列化的,则它们是可序列化的。
  • 它们在创建时拒绝重复的元素/键。
  • 集合元素的迭代顺序是未指定的,并且可能会更改。
  • 它们是基于值的。工厂可以创建新实例或重用现有实例。因此,对这些实例的身份敏感操作、身份哈希码和同步是不可靠的,可以避免使用。

语法

List.of(elements...)
Set.of(elements...)
Map.of(k1, v1, k2, v2)

Example

import java.util.Set;

public class CollectionsTest {
   public static void main(String args[]) {
      System.out.println("Java 9 Introduced a static factory method: of()");
      Set<String> immutableCountrySet = Set.of("India", "England", "South Africa", "Australia");
      System.out.println(immutableCountrySet);
      try {
         immutableCountrySet.add("Newzealand");
      } catch(Exception e) {
         System.out.println("Caught Exception, Adding Entry to Immutable Collection!");
      }
   }
}

Output

Java 9 Introduced a static factory method: of()
[South Africa, India, Australia, England]
Caught Exception, Adding Entry to Immutable Collection!