@Java知识点--ImmutableMap

橙三吉。 提交于 2020-07-27 04:11:09

immutable

  •  [ɪˈmjuːtəbl]
  • adj. 不变的;不可变的;不能变的

Java中的Immutable对象:简单地说,如果一个对象实例不能被更改就是一个Immutable的对象,Java SDK提供的大量值对象,比如String等都是Immutable的对象。

  • 创建ImmutableMap
Map<String,Object> immutableMap = new ImmutableMap.Builder<String,Object>().build();
  • 在创建时放值
Map<String,Object> immutableMap = new ImmutableMap.Builder<String,Object>()
    .put("k1","v1")
    .put("k2","v2")
    .build();
  • 创建后不可变
immutableMap.put("k1","v3");//会抛出java.lang.UnsupportedOperationException

ImmutableMap中key和value均不能为null,放入null值会抛出NPE

ImmutableMap的使用场景

1.适合

  1. 确定性的配置, 比如根据不同的key值得到不同的请求url
  2. 写单元测试

2.不适合

  1. key, value为未知参数, 可能有null产生的情况

3.优化大量的if else

优化大量的if else语句:

/**
 * 定义一些常量Map<?,?>
 */
interface ConstantMap {
    Map<Integer, String> INTEGER_STRING_MAP = new ImmutableMap.Builder<Integer, String>().
                    put(30, "IP地址或地址段").
                    put(31, "端口号或范围").
                    put(32, "IP地址或地址段").
                    put(33, "端口号或范围").
                    .build();
}
//另一种写法
//Map<Integer,String> activityMsgMap = ImmutableMap.<Integer,String>builder().
//            put(30, "IP地址或地址段").
//            put(31, "端口号或范围").
//            put(32, "IP地址或地址段").
//            put(33, "端口号或范围").
//            build();
 
/**
 * guava ImmutableMap 测试实例
 */
public class ImmutableMapTest {
    public static void main(String[] args) {
        immutableMapTest();
    }
 
    /**
     * 测试 guava ImmutableMap
     */
    private static void immutableMapTest() {
        Integer key = 30;
        System.out.println("key = " + key + "的提示语是:" + 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,
        );

注意:of方法入参最多只能有5对,如果添加的数据超过5对,需要改用builder方法.

 

 

 

 

 

 

 

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!