Before Java finds a new writing method, I always initialize List and Map like this:
The code is as follows: |
Copy code |
// Initialize the List List <string> list = new ArrayList </string> <string> (); List. add ("string1 "); List. add ("string2 "); // Some other list. add () code ...... List. add ("stringN "); // Initialize Map Map </string> <string, String> map = new HashMap </string> <string, String> (); Map. put ("key1", "value1 "); Map. put ("key2", "value2 "); //... Some other map. put () code Map. put ("keyN", "valueN "); </String> |
So troublesome ..... One day, the following method is used:
The code is as follows: |
Copy code |
// Initialize the List List <string> list = new ArrayList </string> <string> (){{ Add ("string1 "); Add ("string2 "); // Some other add () code ...... Add ("stringN "); }}; // Initialize Map Map </string> <string, String> map = new HashMap </string> <string, String> (){{ Put ("key1", "value1 "); Put ("key2", "value2 "); //... Some other put () code Put ("keyN", "valueN "); }}; </String> |
Although it seems that there is not much code to write, I personally think this method is much more concise and smooth. Haha ~
For example,Now I have tested the List of two instances, which is simpler.
Method 1:
Use the method of mutual conversion between Array and ArrayList. The code is as follows:
The code is as follows: |
Copy code |
ArrayList <String> list = new ArrayList (Arrays. asList ("Ryan", "Julie", "Bob ")); |
Method 2:
Use the add method of ArrayList to complete initialization assignment. The code is as follows:
The code is as follows: |
Copy code |
List list = new ArrayList <String> (){{ Add (""); Add ("B "); }} |