![]() Immutability is an important concepts which is leveraged in creation of this static factories. For example, a method returning a collection must never return null instead it must return empty collection. They helps us create immutable collections by just calling a method. ConclusionĬollection static factories are extremely easy to use. The new List returned just creates one copy of the specified object which is used to provide view for required length. NCopies method creates an immutable List consisting of n copies of specified element. NCopies(int n, T o) // returns List List fifties = Collections.nCopies(3, 50) Īssert.assertTrue(Arrays.asList(50, 50, 50).equals(fifties)) Īssert.assertTrue(Arrays.asList(1, 2, 50, 50, 50).equals(list)) Static factory for n copies of specified object Specifically they are helpful where a method would accept a collection with single element as a parameter and/or a method which returns collection which can have only single element. This returned collections are immutable which contains only one element. Singleton factory methods provides a way to create a Collection of a single element. singletonMap(K key, V value) // returns MapĬollections.singletonList(Integer.valueOf(42)) Ĭollections.singleton(Integer.valueOf(42)) Ĭollections.singletonMap("Forty Two", Integer.valueOf(42)).Static factory for n copies of specified objectĮmpty Collection is explained here.Below are 3 families of static factories: In this article, I will talk about 3 types of factory method families provided in Collections class. All the methods of Collections class operate on collections and all methods are static. Apparently it is immutable as well, like in example below: List list Arrays.asList('abc', null, 'def') list.removeAll(Collections.![]() It also contains several other interesting methods. Indeed Collections.singletonList(null) is immutable (which is unfortunately hidden in Java 1), but the exception is thrown from your list variable. class is static utility class which contains polymorphic algorithms, static factories and wrapper methods.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |