每天学会一点点(map常量)
map常用的声明方式(使用静态代码块):
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");
另外一种map常量方式:
添加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);//我 } }
程序员的眼里,不止有代码和bug,还有诗与远方和妹子!!!