java匿名內部類

      在不少時候,咱們須要在類的內部初始化一個靜態的Map或者List,而後保存一下常量值提供給類內部方法使用。 
咱們一般的作法是: 
首先初始化一個Map的靜態變量。 
而後在靜態塊添加常量值:變量

  1. private final static Map<String, String> CONSTANT =   
  2.     new HashMap<String, String>();  
  3. static {  
  4.     CONSTANT.put("1", "one");  
  5.     CONSTANT.put("2", "two");  

 

其實還能夠這麼寫:List

  1. private final static Map<String, String> CONSTANT =   
  2.      new HashMap<String, String>() {  
  3.     {  
  4.         put("1", "one");  
  5.         put("2", "two");  
  6.     }  
  7. };  
相關文章
相關標籤/搜索