Create List with One Element in Java

In this post, we will see how to create List with One Element in java..

Using Collections.singletonList()

This is best way to create List with single element if you need an immutable List.

Output

If you try to add element to the list, you will get exception

Using Array.asList() method [ Immuatable list]

Arrays.asList() method can be used to create list with single element. Created list will be immutable list.

If you try to add element to the list, you will get exception

Using new ArrayList with Array.asList() method [ Mutable list]

If you need mutable list, you can use Arrays.asList() and pass the result into new ArrayList.

As this is mutable list, you can add elements to it.

Output

You can also new ArrayList with Collections.singletonList() to create mutable list.

That’s all about how to create ArrayList with one element in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *