I have tested Collections.singleton() method, how to work, but i see that it is not work as what documentation say?
List arraylist= new ArrayList();
arraylist.add("Nguyen");
arraylist.add("Van");
arraylist.add("Jone");
List list = Collections.singletonList(arraylist);// contains three elements
System.out.println(list.size());// right
As what documentation say, The method call returns an immutable list containing only the specified object,A singleton list contains only one element and a singleton HashMap includes only one key. A singleton object is immutable (cannot be modified to add one more element),but when what thing i see in my code that list contains three elements("Nguyen","Van","Jone").
Anybody can explain for me why?? Thanks so much !!
The returned
List
is aList
ofList
s. In this case, the returned list of lists itself is immutable, not the containedList
. Also the returned list contains only one element, not three: thearraylist
variable itself is considered an element and is the only element stored in the list returned byCollections.singletonList
. In other words, the statementCollections.singletonList(arraylist)
does not create a list that contains all elements of the provided list.It would have been much more obvious if you use generics:
What the documentation says is that if you do the following:
then this would throw an exception at runtime.