richs
richs

Reputation: 4769

java one element list

What is the most efficient (performant) way to create a list with just one element?

Upvotes: 6

Views: 220

Answers (3)

M. Justin
M. Justin

Reputation: 21122

As an alternative to Collections.singletonList(T o) mentioned in other answers, there's List.of(E e1). This is the single-element overload of the unmodifiable lists static factory methods, which create unmodifiable lists of arbitrary sizes.

While the current implementation has a small bit of additional overhead compared to singletonList, it is likely to be similarly performant to singletonList in practice.

Upvotes: 0

DwB
DwB

Reputation: 38300

Consider Collections.singletonList() for a list of 1 element.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359826

Just use:

Upvotes: 8

Related Questions