I wanted to create a Java List with a single element. Yet, I wanted to add more elements later. So, I was looking for a couple of ways to do this. So far there are multiple elegant ways to create a list with a single element with a one-liner. Not so much for a modifiable list though. Here's what I gathered so far.
Followings are a few ways of creating a list with strictly a single entry. Can't add more elements.
1. Collections.singletonList()
This returns an immutable list that cannot be modified or add more elements.
// An immutable list containing only the specified object.
List<String> oneEntryList = Collections.singletonList("one");
oneEntryList.add("two"); // throws UnsupportedOperationException
2. Arrays.asList()
This returns a fixed-size list consisting of the number of elements provided as arguments. The number of elements provided would be an array hence the size is fixed to the length of the array.
// Returns a fixed-size list
List<String> oneEntryList = Arrays.asList("one");
oneEntryList.add("two"); // throws UnsupportedOperationException
3. List.of()
Introduced with Java 9. It provides an unmodifiable list consisting of a single element., There's another overloading method that can be provided multiple elements. Still, that'll be unmodifiable.
// An unmodifiable list containing one element
List<String> oneEntryList = List.of("one");
oneEntryList.add("two"); // throws UnsupportedOperationException
If you want to modify the list or need to add more elements later, it'll be something like the below that comes with a new ArrayList.
// A new ArrayList which is modifiable
List<String> oneEntryList = new ArrayList<>(Arrays.asList("one"));
oneEntryList.add("two");
// Conventional way, modifiable ArrayList
List<String> oneEntryList = new ArrayList<>();
oneEntryList.add("one");
Comment below if you find a way to create a modifiable list with a single element in one line.
Comments
Post a Comment