JAVA9 new feature -12-Collection Factory method: Quickly create a read-only collection

Source: Internet
Author: User
1. Official feature

269:convenience Factory Methods for collections

2. Creating a background

To create a read-only, immutable collection, you must construct and assign it, and then add the elements and wrap them up as a non-modifiable collection.

Like what:

Disadvantage: We wrote the five elements in a moment. That is, it cannot be expressed as a single expression.

Of course, we can also handle it a little bit simpler:

3. Instructions for use

Java9 thus introduces a convenient method, which makes similar things easier to express.

List firsnameslist= list.of ("Joe", "Bob", "Bill");

Call the static method of () in the collection to transfer a different number of parameters to this factory method. This feature can be used for set and list, or for a similar form of map. The resulting collection is immutable: adding elements to these collections after creation causes "Unsupportedoperationexception".

Because of the implementation of the interface method in Java 8, these methods can be defined directly within the interface of List,set and map, making it easy to invoke.

4. Examples of Use



Still Silicon Valley interviewer Song Hongkang
Links: https://www.jianshu.com/p/9660482286d4
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

JAVA9 new feature -12-Collection Factory method: Quickly create a read-only collection

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.