Collections.singleton() methods does not work as documentation?

2k Views Asked by At

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 !!

1

There are 1 best solutions below

6
On BEST ANSWER

The returned List is a List of Lists. In this case, the returned list of lists itself is immutable, not the contained List. Also the returned list contains only one element, not three: the arraylist variable itself is considered an element and is the only element stored in the list returned by Collections.singletonList. In other words, the statement Collections.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:

List<String> arraylist= new ArrayList<>();
arraylist.add("Nguyen");
arraylist.add("Van");
arraylist.add("Jone");
List<List<String>> list = Collections.singletonList(arraylist);

What the documentation says is that if you do the following:

List list = Collections.singletonList(arraylist);
list.add(new ArrayList());

then this would throw an exception at runtime.