ImmutableMap代替ifelse和switch

   //初始化
    Map<Integer, String> INTEGER_STRING_MAP =
            new ImmutableMap.Builder<Integer, String>().
                    put(1, "1").
                    put(31, "31").
                    put(32, "32").build();

源码分析:public abstract class ImmutableMap<K, V> implements Map<K, V>, Serializable

ImmutableMap是一个抽象类实现了Map接口,并实现了其中一些map的方法(抽象类实现接口的额好处:如果普通类实现接口就必须实现所有的接口,但抽象类实现接口可以选择性实现,降低耦合性)。

源码:
  final transient K singleKey;
  final transient V singleValue;

  SingletonImmutableBiMap(K singleKey, V singleValue) {
    checkEntryNotNull(singleKey, singleValue);
    this.singleKey = singleKey;
    this.singleValue = singleValue;
  }

因为ImmutableMap的value和key值都是用final修饰的,所以他不能去修改里面的值。相当于一个常量

猜你喜欢

转载自blog.csdn.net/m0_46086429/article/details/106626779