Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Leandro Lima
Leandro Lima

Posted on

     

[Code Compare] 2. Collections.singletonList vs List.of

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);}
Enter fullscreen modeExit fullscreen mode

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:

  1. Inline implementation: Initialize with the desired element in a single line.
  2. Immutability: The list's size and content of its single element cannot be changed.
  3. Memory Allocation: TheSingletonList class contains only one field for the single element.
  4. CPU usage: TheSingletonList 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);}
Enter fullscreen modeExit fullscreen mode

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);}
Enter fullscreen modeExit fullscreen mode

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;}...}
Enter fullscreen modeExit fullscreen mode
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();}
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Adoro interagir, aprender e ensinar! Sou apaixonado com Java e programo há mais de dez anos nessa linguagem. Amo dança de salão, cervejas artesanais, queijos mineiros maturados e um bom café!
  • Location
    Belo Horizonte, Brazil
  • Education
    Bacharel em Eng. Controle e Automação pela UFMG
  • Work
    Software Engineer at Iteris/Pagbank
  • Joined

More fromLeandro Lima

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp