In this serie of posts, I'm comparing different ways to code the same functionality.Last post comparedCollections.singletonList andArrayList for creating a single-element list.
In this post I'll compareCollections.singletonList
whith another well-knownFactory Method,List.of.
Collections::singletonList
Method signature
public static <T> List<T> singletonList(T o)
publicstaticvoidmain(String[]args){finalvaraddresses=Collections.singletonList(newAddress("742 Evergreen Terrace","Springfield","New York","13468","US"));System.out.println(addresses);}
Description
This method returns an immutable list containing only the specified object. It was introduced in Java 1.3. The advantages over ArrayList were covered in the last post, but to recap:
- Inline implementation: Initialize with the desired element in a single line.
- Immutability: The list's size and content of its single element cannot be changed.
- Memory Allocation: The
SingletonList
class contains only one field for the single element. - CPU usage: The
SingletonList
constructor accepts the single element as a parameter, requiring no resizing or array maniputalion.
List::of
Method signature
static <E> List<E> of()
publicstaticvoidmain(String[]args){finalvaraddresses2=List.of(newAddress("1007 Mountain Drive","Bristol Township","New Jersey",null,"US"));System.out.println(addresses2);}
Description
TheList.of(E e)
method is also a Factory Method that returns an unmodifiable list. UnlikeCollections.singletonList(E e)
, which supports only one element,List.of
supports 0 to 10 elements, as well as arrays with multiple elements. It was introduced in Java 9, 17 years aftersingletonList
.
It's interesting note that, unlikeSingletonList
, which has the comment:
Returns animmutable list containing only the specified object.
theArray.of
states that it is anUnmodifiable List:
Returns an unmodifiable list containing one element.
This reflects a new understand of immutability of collections. According thisdocumentation:
A collection is considered unmodifiable if elements cannot be added, removed, or replaced. However, an unmodifiable collection is only immutable if the elements contained in the collection are immutable.
Dispite this differences in terminology, both factory methods have almost the same functionality. Looking deeper inside theUnmodifiableList
, we can find:
static<E>List<E>of(Ee1){returnnewImmutableCollections.List12<>(e1);}
What a surprise, they went with the not-so-precise termImmutable, though!
staticfinalclassList12<E>extendsAbstractImmutableList<E>implementsSerializable{@StableprivatefinalEe0;@StableprivatefinalEe1;List12(Ee0){this.e0=Objects.requireNonNull(e0);this.e1=null;}...}
staticabstractclassAbstractImmutableList<E>extendsAbstractImmutableCollection<E>implementsList<E>,RandomAccess{// all mutating methods throw UnsupportedOperationException@Overridepublicvoidadd(intindex,Eelement){throwuoe();}@OverridepublicbooleanaddAll(intindex,Collection<?extendsE>c){throwuoe();}@OverridepublicEremove(intindex){throwuoe();}@OverridepublicvoidreplaceAll(UnaryOperator<E>operator){throwuoe();}@OverridepublicEset(intindex,Eelement){throwuoe();}@Overridepublicvoidsort(Comparator<?superE>c){throwuoe();}
The only difference is thatList12
has two fields for potentially two elements, which also results in a negligible memory footprint unless dealing with large objects.
Conclusion
This time, we comparedCollections.singletonList
andList.of
factory methods to create a single-element list. We discussed about the semantics ofimmutable andunmodifiable and showed that both methods are efficient, concise, and resource-light. If you can use a more recent Java version, it's prefferable for its familiarity, clarity and because we useList
interface much more thanCollections
. If restritcted to an older Java version,Collections.singletonList
remains a solid choice.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse