@Java knowledge point -- immutable map

immutable

  •  [ɪˈmjuːtəbl]
  • adj. Unchanging; immutable; immutable

Immutable object in Java: in short, if an object instance cannot be changed, it is an immutable object. A large number of value objects provided by the Java SDK, such as String, are immutable objects.

  • Create immutable map
Map<String,Object> immutableMap = new ImmutableMap.Builder<String,Object>().build();
  • Place values on Creation
Map<String,Object> immutableMap = new ImmutableMap.Builder<String,Object>()
    .put("k1","v1")
    .put("k2","v2")
    .build();
  • Immutable after creation
immutableMap.put("k1","v3");//Java.lang.unsupported operation exception will be thrown

Both key and value in immutable map cannot be null. Putting a null value will throw NPE

Usage scenarios of immutable map

1. Suitable

  1. Deterministic configuration, such as different request URLs according to different key values
  2. Write unit test

2. Not suitable

  1. Key and value are unknown parameters. null may occur

3. Optimize a large number of if else

Optimize a large number of if else sentence:

/**
 * Define some constants map <?,? >
 */
interface ConstantMap {
    Map<Integer, String> INTEGER_STRING_MAP = new ImmutableMap.Builder<Integer, String>().
                    put(30, "IP Address or address segment").
                    put(31, "Port number or range").
                    put(32, "IP Address or address segment").
                    put(33, "Port number or range").
                    .build();
}
//Another way of writing
//Map<Integer,String> activityMsgMap = ImmutableMap.<Integer,String>builder().
//            put(30, "IP address or address segment")
//            put(31, "port number or range")
//            put(32, "IP address or address segment")
//            put(33, "port number or range")
//            build();
 
/**
 * guava ImmutableMap Test case
 */
public class ImmutableMapTest {
    public static void main(String[] args) {
        immutableMapTest();
    }
 
    /**
     * Test guava immutable map
     */
    private static void immutableMapTest() {
        Integer key = 30;
        System.out.println("key = " + key + "The prompt of is:" + ConstantMap.INTEGER_STRING_MAP.get(key));
    }
}

4.ImmutableMap.of

  /**
   * Returns the empty map. This map behaves and performs comparably to
   * {@link Collections#emptyMap}, and is preferable mainly for consistency
   * and maintainability of your code.
   */
  public static <K, V> ImmutableMap<K, V> of() {
    return ImmutableBiMap.of();
  }
 
  /**
   * Returns an immutable map containing a single entry. This map behaves and
   * performs comparably to {@link Collections#singletonMap} but will not accept
   * a null key or value. It is preferable mainly for consistency and
   * maintainability of your code.
   */
  public static <K, V> ImmutableMap<K, V> of(K k1, V v1) {
    return ImmutableBiMap.of(k1, v1);
  }
 
  /**
   * Returns an immutable map containing the given entries, in order.
   *
   * @throws IllegalArgumentException if duplicate keys are provided
   */
  public static <K, V> ImmutableMap<K, V> of(K k1, V v1, K k2, V v2) {
    return new RegularImmutableMap<K, V>(entryOf(k1, v1), entryOf(k2, v2));
  }
 
  /**
   * Returns an immutable map containing the given entries, in order.
   *
   * @throws IllegalArgumentException if duplicate keys are provided
   */
  public static <K, V> ImmutableMap<K, V> of(
      K k1, V v1, K k2, V v2, K k3, V v3) {
    return new RegularImmutableMap<K, V>(
        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
  }
 
  /**
   * Returns an immutable map containing the given entries, in order.
   *
   * @throws IllegalArgumentException if duplicate keys are provided
   */
  public static <K, V> ImmutableMap<K, V> of(
      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
    return new RegularImmutableMap<K, V>(
        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
  }
 
  /**
   * Returns an immutable map containing the given entries, in order.
   *
   * @throws IllegalArgumentException if duplicate keys are provided
   */
  public static <K, V> ImmutableMap<K, V> of(
      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
    return new RegularImmutableMap<K, V>(entryOf(k1, v1),
        entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
  }
 
  // looking for of() with > 5 entries? Use the builder instead.
Map<String, Integer> typeMap = ImmutableMap.of(
                "1", 1,
                "2", 2,
                "3", 3,
        );

Note: the of method can only have 5 pairs of input parameters at most. If more than 5 pairs of data are added, the builder method needs to be used instead

Tags: Programming Java SDK

Posted on Fri, 15 May 2020 07:59:08 -0700 by samadams83