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
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); }
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
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); }
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); } </e></e>
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; } ... } </e></e>
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(); } </e></e></e></e>
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!

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
