标签:常用 使用 nbsp port uil 实现 put 代码块 table
public final static Map map = new HashMap(); static { map.put("key1", "value1"); map.put("key2", "value2"); }
public class ConstMap { public static final Map<String, String> MAP_CONST = new HashMap(){{ put("",""); put("1","我"); put("2","你"); put("3","他"); }}; }
这种方式,相当于重载HashMap的一个匿名实现。向原有的HashMap中添加了一个匿名构造方法。
List/Set变量的声明方式:
public final static List list = Arrays.asList("111", "222");
添加guava依赖:
<!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>23.0</version> </dependency>
代码:
import com.google.common.collect.ImmutableMap; import java.util.Map; public interface ConstantMap { Map<String,String> MAP_TEST = new ImmutableMap.Builder<String,String>() .put("","") .put("1","我") .put("2","你") .build(); }
测试结果:
public class Test { public static void main(String[] args) { String name = ConstantMap.MAP_TEST.get("1"); System.out.println(name);//我 } }
标签:常用 使用 nbsp port uil 实现 put 代码块 table
原文地址:https://www.cnblogs.com/heqiyoujing/p/10392443.html