Map Common initialization methods for collections :

Map<String, String> map = new HashMap<String, String>();
map.put("Name", "June");
map.put("QQ", "2572073701");

Today I see this way of writing :

 /** Cannot retry exception Parameter error **/
public static final Map<String, String> SMS_PARAM_ERROR_UNRETRY =
new HashMap<String, String>() {
put(SMS_RESP_208001, " Parameter error ");
put(SMS_RESP_208101, " There are duplicate request data ");
put(SMS_RESP_208102, " Resource competition ");
put(SMS_RESP_208200, " Database exception ");
put(SMS_RESP_208500, " Cache exception ");

The front thought it was jdk7 perhaps jdk8 New features

I'll look at the data later by using inheritance 、 Code block 、 Implementation of inner class

It's equivalent to creating a HashMap Subclass object of , And there is an instance code block in this subclass to do an initialization assignment operation , The instance method can be called at will in the instance code block .

Code :

 Map<String, String> map1 = new HashMap<String, String>() {
put("Name", "June");
put("QQ", "");
for(Map.Entry<String, String> entry : map1.entrySet() ){
System.out.println(entry.getKey() + ", " + entry.getValue() );

Decompile :

package kunpu.test1;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry; public class SimpleCollectCreateDemo1
public static void main(String[] args)
Map<String, String> map1 = new HashMap() {};
for (Map.Entry<String, String> entry : map1.entrySet()) {
System.out.println((String)entry.getKey() + ", " + (String)entry.getValue());
package kunpu.test1;
import java.util.HashMap;
final class SimpleCollectCreateDemo1$
extends HashMap<String, String>
put("Name", "June");
put("QQ", "");

Empathy ,ArrayList Etc. can be initialized in the same way :

List<String> stringList = new ArrayList<String>(){
for(String s : stringList){

stay jdk1.7 In the new features of java Enhanced support for collections :

Abandoned Java Implementation class of collection interface , Such as :ArrayList、HashSet and HashMap. It's a direct use of []、{} In the form of objects , use [] In the form of an index 、 Key values to get the objects in the collection , as follows :

So the way to initialize a collection is not just rigid .

4、 Potential problems in literary and artistic writing
    The advantage of literary and artistic writing mentioned at the beginning of the article is obvious . Here's a list of the disadvantages of this method , If the object is to be serialized , May cause serialization failure .
  1. This is the way to declare anonymous inner classes , So the reference holds a reference to an external class . So when serializing this collection, external classes are also unconsciously serialized , When an external class does not implement serialize Interface , You're going to report a mistake .

2. In the above example , It's actually a statement that inherits from HashMap Subclasses of . However, some serialization methods , For example, through Gson Serialize to json, Or serialize it to xml when , Methods provided in the class library , It's impossible to serialize Hashset perhaps HashMap Of a subclass of , This leads to the failure of serialization . terms of settlement : Reinitialize to a HashMap object :

So you can initialize it normally .

Reference link :

The pattern of initializing a collection new HashMap<String, String>{ {put("str1":"abc");} }( turn ) More articles about

  1. How to use List&lt;HashMap&lt;String, String&gt;&gt; Explain in detail

    scene : To loop the interface Table Data sources and exports Excel Data sources . explain : List<HashMap<String,String>>  List Each of these is a HashMap Ha ...

  2. Java: decompose List&lt;HashMap&lt;String, String&gt;&gt;

    decompose List<HashMap<String, String>> Methods : List<HashMap<String, String>> mapList; ...

  3. take ArrayList&lt;HashMap&lt;String, String&gt;&gt; To ArrayList&lt;Bundle&gt; Type of solution

    Bundle Is a data format that uses key value pairs to store , And we usually use... In our programs HashMap Store the data . In development , adopt Http Request to get JSONArray Return value of type , I choose to use ArrayList<HashMa ...

  4. List&lt;HashMap&lt;String,String&gt;&gt; list, according to hashmap Sort the values of a key in

    source // have access to Collections.sort(List list, Comparator c) To achieve Here is an example hash ...

  5. java Self study 4 period ——:Scanner class 、 Anonymous object Introduction 、Random class 、ArrayList aggregate 、 Standard class format 、String class 、static static state 、Arrays Tool class 、Math class (1)

    One .Scanner class 1.api brief introduction : Application programming interface 2.Scanner class : effect : Get the data from the keyboard Location : java.util.Scanner. Use : Use the member method nextInt() and ne ...

  6. [Java aggregate ] Understand thoroughly HashMap,HashTable,ConcurrentHashMap The connection between .

    notes : Today I read an article about hashMap,hashTable,concurrentHashMap A very thorough article , Thanks for sharing . Original address : ...

  7. Java Collection Series 10 And HashMap Detailed introduction ( The source code parsing ) And use examples

    Summary This chapter , We are right. HashMap To study . Let's start with HashMap There is a general understanding of , Then learn its source code , Finally, learn to use it through examples HashMap. The content includes : The first 1 part HashMap Introduce the second 2 part HashMa ...

  8. aggregate ( Four )HashMap

    Previous List, Talked about it. ArrayList.LinkedList, At last, I talked about CopyOnWriteArrayList, In terms of the first two , It reflects two thoughts : (1)ArrayList In the form of an array , Order insert . check ...

  9. java Set the framework of java HashMap Code parsing

     java Set the framework of java HashMap Code parsing article Java After the collection framework review , Specific collection class code , First of all, with both familiar and unfamiliar HashMap Start . Derived from ...

Random recommendation

  1. The project uses icarouls Classes and UIEffectDesignerView class , Menu skills , conceived ( Jin Fangyuan )

    // //  MenuHomeViewController.m //  HFYS // //  Created by Showsoft_002 on 13-8-14. //  Copyright (c ...

  2. java Class loader -Tomcat Class loader

    In the above , The system class loader and its related mechanisms have been introduced , We also customize the way of class loader . The next step is to tomcat6 Take... For example tomat How to use the custom class loader .( This introduction is based on tomcat6.0.41, Different versions can ...

  3. iOS Sandbox (sandbox) Mechanisms and file operations

    This article refers to The introduction in this article , Respect for the original . 1.IOS Sandbox mechanism IOS Applications can only create files in this application ...

  4. freemarker example 2

    Here is a simple process of using the project :1. Use myeclipse Create a web project testFM2. Download to jar package (freemarker-2.3.9.jar) Put it in /WebRoot/WEB-INF/li ...

  5. Python django admin Replace the form control

    Test version : Python 2.7 Django 1.6.2 from django.db import models class Article(models.Model): ti ...

  6. Entity - Use EF Add, delete, modify and check the framework - Model First

    Model First : First create the database entity model , Then add, delete, modify and query the database . The basic steps are the same , Referable <Entity - Use EF Add, delete, modify and check the framework - Database First > The difference is , In the process of creating database entity model ...

  7. java call oracle stored procedure , Return result set

    package; import java.sql.CallableStatement; import java.sql.Connection; import java. ...

  8. Generate pdf

    /** * Generate pdf * @param string $html What needs to be generated */ function pdf($html='<h1 style="color:red"& ...

  9. ldap Configure a series of :ldap Installation

    ldap Installation ldap An introduction to the LDAP Is lightweight directory access protocol , The full English name is Lightweight Directory Access Protocol, It's generally called LDAP. It is based on X.500 The standard , But Jane ...

  10. [ Physics and PDEs] The first 2 Chapter one 2 section Viscous fluid dynamics equations 2.6 One dimensional viscous heat conduction hydrodynamics equations

    One dimensional viscous heat conduction hydrodynamics equations : $$\beex \bea \cfrac{\p\rho}{\p t}+\cfrac{\p }{\p x}(\rho u)&=0,\\ \cfrac{\p u}{ ...