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