
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the conditions for Collection factory methods in Java 9?
In Java 9, factory methods have been added to Collections API. We can create an unmodifiable list, set and map collection objects in order to reduce the number of lines of code by using it. The List.of(), Set.of(), Map.of(), and Map.ofEntries() are the static factory methods provides convenient way of creating immutable collections.
Below are the conditions for Collection factory methods:
- They are structurally immutable.
- They disallow null elements or null keys.
- They are serializable if all elements are serializable.
- They reject duplicate elements/keys at creation time.
- The Iteration order of set elements is unspecified and is subject to change.
- They are value-based. Factories are free to create new instances or reuse existing ones. Therefore, Identity-sensitive operations on these instances, Identity hash code, and synchronization are unreliable and can be avoided.
Syntax
List.of(elements...) Set.of(elements...) Map.of(k1, v1, k2, v2)
Example
import java.util.Set; public class CollectionsTest { public static void main(String args[]) { System.out.println("Java 9 Introduced a static factory method: of()"); Set<String> immutableCountrySet = Set.of("India", "England", "South Africa", "Australia"); System.out.println(immutableCountrySet); try { immutableCountrySet.add("Newzealand"); } catch(Exception e) { System.out.println("Caught Exception, Adding Entry to Immutable Collection!"); } } }
Output
Java 9 Introduced a static factory method: of() [South Africa, India, Australia, England] Caught Exception, Adding Entry to Immutable Collection!
- Related Questions & Answers
- Which factory methods have added for collections in Java 9?
- What are the methods for expressing attribute test conditions?
- What are the rules for private methods in an interface in Java 9?
- What are the new methods added to Process API in Java 9?
- What are new methods added to the String class in Java 9?
- @SafeVarargs annotation for private methods in Java 9?
- What are the improvements for @Deprecated annotation in Java 9?
- What are the advantages of private methods in an interface in Java 9?
- What are the rules for the Subscriber interface in Java 9?
- What are the rules for the Subscription interface in Java 9?
- What are the rules for the Publisher interface in Java 9?
- What are the new methods added to an Optional class in Java 9?
- What are new methods have added to the Arrays class in Java 9?
- What are JavaScript Factory Functions?
- What are the improvements for try-with-resources in Java 9?
Advertisements