Java 不可变型Map

Java 不可变型Map

  • ImmutableMap,顾名思义,是Map的一种类型,是不可变的。它意味着Map的内容在声明后是固定或不变的,也就是说,它们是 只读的
  • 如果试图在Map中添加、删除和更新元素,就会抛出 UnsupportedOperationException
  • ImmutableMap也不允许空元素。
  • 如果试图用空元素创建ImmutableMap,会抛出 NullPointerException 。如果试图在Map中添加空元素,会产生 不支持操作的异常

ImmutableMap的优点

  • 它们是 线程安全的
  • 它们具有 内存效率
  • 由于它们是不可变的,因此它们可以毫无问题地 传递给第三方库

请注意 ,它是一个不可变的集合,而不是不可变对象的集合,所以它里面的对象可以被修改。

类声明

@GwtCompatible(serializable=true,
               emulated=true)
public abstract class ImmutableMap
extends Object
implements Map, Serializable

类的层次结构

java.lang.Object
  ↳ com.google.common.collect.ImmutableMap 

创建ImmutableMap
ImmutableMap可以通过各种方法创建。这些方法包括

  1. 使用Guava的copyOf()函数从现有的Map中获取
    // Below is the Java program to create ImmutableMap
      
    import com.google.common.collect.ImmutableMap;
    import java.util.HashMap;
    import java.util.Map;
      
    class MapUtil {
      
        // Function to create ImmutableMap from Map
        public static <K, T> void iMap(Map<K, T> map)
        {
            // Create ImmutableMap from Map using copyOf()
            ImmutableMap<K, T> immutableMap = ImmutableMap.copyOf(map);
      
            // Print the ImmutableMap
            System.out.println(immutableMap);
        }
      
        public static void main(String[] args)
        {
            Map<Integer, String> map = new HashMap<Integer, String>();
            map.put(1, "Geeks");
            map.put(2, "For");
            map.put(3, "Geeks");
            iMap(map);
        }
    }

输出:

{1=Geeks, 2=For, 3=Geeks}
  1. 使用Guava的of()函数创建ImmutableMap
    // Below is the Java program to create ImmutableMap
    import com.google.common.collect.ImmutableMap;
    import java.util.HashMap;
    import java.util.Map;
      
    class MapUtil {
      
        // Function to create ImmutableMap
        public static void createImmutableMap()
        {
            // Create ImmutableMap using of()
            ImmutableMap<Integer, String> immutableMap = ImmutableMap.of(
                1, "Geeks",
                2, "For",
                3, "Geeks");
      
            // Print the ImmutableMap
            System.out.println(immutableMap);
        }
      
        public static void main(String[] args)
        {
            createImmutableMap();
        }
    }

输出:

{1=Geeks, 2=For, 3=Geeks}
  1. 使用Java 9工厂的Of()方法

在Java中,与Set、Map或List一起使用of()来创建一个Immutable Map。

请注意:下面的程序是Java 9的,因此你需要一个Java 9的编译器来运行它们

// Java code illustrating of() method to
// create a ImmutableSet
import java.util.*;
import com.google.common.collect.ImmutableMap;
  
class GfG {
    public static void main(String args[])
    {
        // non-empty immutable set
        Map<Integer, String> map = Map.of(
            1, "Geeks",
            2, "For",
            3, "Geeks");
  
        // Let's print the set
        System.out.println(map);
    }
}

输出:

{1=Geeks, 2=For, 3=Geeks}
  1. 使用ImmutableMap的Builder()

在Guava中,ImmnutableMap类提供了一个函数Builder()。通过这个函数,可以创建一个新的ImmutableMap,或者
可以从现有的Map中创建一个ImmutableMap,也可以同时创建两个。

  • 创建一个新的ImmutableMap
// Java code illustrating of() method to
// create a ImmutableSet
import java.util.*;
import com.google.common.collect.ImmutableMap;
  
class GfG {
    public static void main(String args[])
    {
        // non-empty immutable set
        ImmutableMap<Integer, String> imap = 
                         ImmutableMap.<Integer, String>builder()
                                                 .put(1, "Geeks")
                                                 .put(2, "For")
                                                 .put(3, "Geeks")
                                                 .build();
  
        // Let's print the set
        System.out.println(imap);
    }
}

输出:

{1=Geeks, 2=For, 3=Geeks}
  • 从现有的Map创建一个ImmutableMap
// Java code illustrating of() method to
// create a ImmutableSet
import java.util.*;
import com.google.common.collect.ImmutableMap;
  
class GfG {
    public static void main(String args[])
    {
        // non-empty immutable set
        Map<Integer, String> map = Map.of(1, "Geeks",
                                          2, "For",
                                          3, "Geeks");
        ImmutableMap<Integer, String> imap = 
                       ImmutableMap.<Integer, String>builder()
                                                 .putAll(map)
                                                 .build();
  
        // Let's print the set
        System.out.println(imap);
    }
}

输出:

{1=Geeks, 2=For, 3=Geeks}
  • 创建一个新的ImmutableMap,包括现有的Map
// Java code illustrating of() method to
// create a ImmutableSet
import java.util.*;
import com.google.common.collect.ImmutableMap;
  
class GfG {
    public static void main(String args[])
    {
        // non-empty immutable set
        Map<Integer, String> map = Map.of(1, "Geeks",
                                          2, "For",
                                          3, "Geeks");
        ImmutableMap<Integer, String> imap = 
                     ImmutableMap.<Integer, String>builder()
                                               .putAll(map)
                                         .put(4, "Computer")
                                           .put(5, "Portal")
                                                   .build();
  
        // Let's print the set
        System.out.println(imap);
    }
}

输出:

{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}

尝试改变ImmutableMap

如前所述,下面的程序会抛出 UnsupportedOperationException

// Java code to show that UnsupportedOperationException
// will be thrown when ImmutableMap is modified.
import java.util.*;
  
class GfG {
    public static void main(String args[])
    {
        // empty immutable map
        Map<Integer, String> map = Map.of();
  
        // Lets try adding element in these set
        map.put(1, "Geeks");
        map.put(2, "For");
        map.put(3, "Geeks");
    }
}

输出:

Exception in thread "main" java.lang.UnsupportedOperationException
    at com.google.common.collect.ImmutableCollection.add(ImmutableCollection.java:218)
    at ImmutableListDemo.main(Main.java:16)

它与Collections.unmodifiableMap()有什么不同?

Collections.unmodifiableMap在同一个现有的Map周围创建了一个封装器,这样就不能用封装器来修改它。但是我们仍然可以改变原来的Map。

// Java program to demonstrate that a Map created using
// Collections.unmodifiableMap() can be modified indirectly.
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(1, "Geeks");
        map.put(2, "For");
        map.put(3, "Geeks");
  
        // Create ImmutableMap from Map using copyOf()
        Map<Integer, String> imap = Collections.unmodifiableMap(map);
  
        // We change map and the changes reflect in imap.
        map.put(4, "Computer");
        map.put(5, "Portal");
  
        System.out.println(imap);
    }
}

输出:

{1=Geeks, 2=For, 3=Geeks, 4=Computer, 5=Portal}

如果我们从一个现有的Map创建一个ImmutableMap并改变现有的Map,ImmutableMap不会改变,因为创建了一个副本。

// Below is a Java program for
// Creating an immutable Map using copyOf()
// and modifying original Map.
import java.io.*;
import java.util.*;
import com.google.common.collect.ImmutableMap;
  
class GFG {
    public static void main(String[] args)
    {
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(1, "Geeks");
        map.put(2, "For");
        map.put(3, "Geeks");
  
        // Create ImmutableMap from Map using copyOf()
        ImmutableMap<Integer, String> imap = ImmutableMap.copyOf(map);
  
        // We change map and the changes wont reflect in imap.
        map.put(4, "Computer");
        map.put(5, "Portal");
  
        System.out.println(imap);
    }
}

输出:

{1=Geeks, 2=For, 3=Geeks}

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程