The Collections class provides methods to create collections that have only one element.
Returns Set, List, and Map with one element for each.
import java.util.Collections;
import java.util.Set;
import java.util.List;
import java.util.Map;
import java.util.Collections.ImmutableSet;
class CollectionsSingleton {
public static void main(String args[]) {
Set<String> s = Collections.singleton("a");
// s.add("b"); // UnsupportedOperationException
System.out.println(s);
List<String> l = Collections.singletonList("a");
System.out.println(l);
Map<Integer, String> m = Collections.singletonMap(0, "a");
System.out.println(m);
}
}
The returned collection is immutable. An UnsupportedOperationException is thrown when trying to add an element or the like.