Some methods of listing and Map initialization in Java

Source: Internet
Author: User

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 ");
}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.