在Java 9中创建不可变映射的工厂方法

在Java 9中,Java语言添加了一些特性,不可变映射的工厂方法就是其中之一。 不变映射的特征:

null
  • 顾名思义,这些地图是不可变的。
  • 如果试图在地图中添加、删除和更新元素,我们将有UnsupportedOperationException。
  • 不可变映射也不允许空元素。
  • 如果有人试图用null元素创建一个不可变的映射,我们将有NullPointerException。如果试图在映射中添加null元素,我们将有UnsupportedOperationException。

在Java8中创建不可变映射

为了在Java8中创建不可变映射,我们使用java。util。不可修改映射(Map)方法。 不可修改地图(地图地图): 此方法返回指定映射的不可修改视图。此方法允许模块为用户提供对内部地图的“只读”访问。

Syntax: public static  Map unmodifiableMap(Map map)
Returns: an unmodifiable view of the specified map.
Exception: NA

不可变空和无空映射的Java代码:

// Java code illustrating immutable map in java 8
import java.util.*;
class ImmutableListDemo
{
public static void main(String args[])
{
// empty map
Map<Integer, String> empty = new HashMap();
Map immutable1 = Collections.unmodifiableMap(empty);
// non-empty map
Map<Integer, String> non_empty = new HashMap();
non_empty.put( 1 , "ide" );
Map immutable2 = Collections.unmodifiableMap(non_empty);
// adding key-value pair in these immutable map
immutable1.put( 1 , "gfg" );
immutable2.put( 2 , "quiz" );
}
}


上面的代码将生成异常,因为我们试图在不可变映射中添加键值对。

Runtime Error : Exception in thread "main" 
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
at ImmutableListDemo.main(File.java:17)

在Java9中创建不可变映射

为了在Java9中创建不可变映射,我们使用 of() 入口() 方法 在Java 9中创建不可变映射的Java代码:

// Java code illustrating of() method
import java.util.*;
class ImmutableListDemo
{
public static void main(String args[])
{
// empty immutable map
Map<Integer, String> immutable1 = Map.of();
// non-empty immutable map
Map<Integer, String> immutable2 = Map.of( 1 , "ide" , 2 , "quiz" );
// adding key-value pair in these immutable map
immutable1.put( 1 , "gfg" );
immutable2.put( 3 , "contribute" );
}
}


运行上述代码后,我们将出现UnsupportedOperationException。 使用map创建不可变映射的Java代码。Java 9中的ofEntries()方法:

// Java code illustrating ofEntries method
import java.util.*;
import java.util.Map.Entry;
class ImmutableListDemo
{
public static void main(String args[])
{
// empty immutable map
Map<Integer, String> immutable = Map.ofEntries();
// non-empty immutable map
Map.Entry<Integer, String> entry1 = Map.entry( 1 , "gfg" );
Map.Entry<Integer, String> entry2 = Map.entry( 2 , "contribute" );
Map<Integer, String> immubatleMap = Map.ofEntries(entry1,
entry2);
}
}


sof()和ofEntries()是在java 9中用于创建不可变映射的方法。

本文由 阿布舍克·维马 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享