@param the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.
import java.util.*;
public class HelloWorld {
public static void main(String args[]) {
// create an array of string objs
String initList[] = { "One", "Two", "Four", "One",};
// create one list
List list = new ArrayList(Arrays.asList(initList));
System.out.println("List value before: "+list);
// create singleton list
list = Collections.singletonList("OnlyOneElement");
list.add("five"); //throws UnsupportedOperationException
System.out.println("List value after: "+list);
}
}
Úselo cuando el código espere una lista de solo lectura, pero solo quiere pasar un elemento en él. singletonList
es (hilo) seguro y rápido.
Aquí hay un ejemplo de cómo puede ser útil: http://stackoverflow.com/a/1239631/360811 – shabunc
posible duplicación de [Arrays.asList() vs Collections.singletonList()] (http://stackoverflow.com/questions/26027396/arrays-aslist-vs-collections-singletonlist) – sschuberth