Home Java javaTutorial [Code Compare] Collections.singletonList vs List.of

[Code Compare] Collections.singletonList vs List.of

Aug 07, 2024 am 09:24 AM

[Code Compare] Collections.singletonList vs List.of

In this serie of posts, I'm comparing different ways to code the same functionality. Last post compared Collections.singletonList and ArrayList for creating a single-element list.

In this post I'll compare Collections.singletonList whith another well-known Factory Method, List.of.

Collections::singletonList

Method signature

public static List singletonList(T o)

  public static void main(String[] args) {
    final var addresses = Collections.singletonList(
        new Address(
            "742 Evergreen Terrace",
            "Springfield",
            "New York",
            "13468",
            "US"
        ));

    System.out.println(addresses);
  }
Copy after login

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: The SingletonList class contains only one field for the single element.
  4. CPU usage: The SingletonList constructor accepts the single element as a parameter, requiring no resizing or array maniputalion.

List::of

Method signature

static List of()

  public static void main(String[] args) {
     final var addresses2 = List.of(
        new Address(
            "1007 Mountain Drive",
            "Bristol Township",
            "New Jersey",
            null,
            "US"
        ));

    System.out.println(addresses2);
  }
Copy after login

Description

The List.of(E e) method is also a Factory Method that returns an unmodifiable list. Unlike Collections.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 after singletonList.

It's interesting note that, unlike SingletonList, which has the comment:

Returns an immutable list containing only the specified object.

the Array.of states that it is an Unmodifiable List:

Returns an unmodifiable list containing one element.

This reflects a new understand of immutability of collections. According this documentation:

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 the UnmodifiableList, we can find:

  static <E> List<E> of(E e1) {
      return new ImmutableCollections.List12<>(e1);
  }
Copy after login

What a surprise, they went with the not-so-precise term Immutable, though!

  static final class List12<E> extends     
    AbstractImmutableList<E> implements Serializable {

        @Stable
        private final E e0;

        @Stable
        private final E e1;

        List12(E e0) {
            this.e0 = Objects.requireNonNull(e0);
            this.e1 = null;
        }
        ...
    }
Copy after login
static abstract class AbstractImmutableList<E> extends
  AbstractImmutableCollection<E> implements List<E>, RandomAccess {

      // all mutating methods throw UnsupportedOperationException
      @Override public void    add(int index, E element) { throw uoe(); }
      @Override public boolean addAll(int index, Collection<? extends E> c) { throw uoe(); }
      @Override public E       remove(int index) { throw uoe(); }
      @Override public void    replaceAll(UnaryOperator<E> operator) { throw uoe(); }
      @Override public E       set(int index, E element) { throw uoe(); }
      @Override public void    sort(Comparator<? super E> c) { throw uoe(); }
Copy after login

The only difference is that List12 has two fields for potentially two elements, which also results in a negligible memory footprint unless dealing with large objects.

Conclusion

This time, we compared Collections.singletonList and List.of factory methods to create a single-element list. We discussed about the semantics of immutable and unmodifiable 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 use List interface much more than Collections. If restritcted to an older Java version, Collections.singletonList remains a solid choice.

The above is the detailed content of [Code Compare] Collections.singletonList vs List.of. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles