Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what does collections.singletonlist do

 
Praveen Seluka
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI all

what does the collections.singletonlist(Object o) method do?

What do we mean by the term immutable list and singleton list?
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An immutable List (also referred to as an unmodifiable List) cannot have it's contents changed. The methods to add or remove items will throw exceptions if you tr to alter the contents.

A singleton List contains only that item and cannot be altered.
 
Praveen Seluka
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya I understood the terms.thanks
I came across this code.But why do we create a list with a single object.
Can you say what is the advantage in using collections.singletonlist() ?

Thanks
Praveen SP
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want an empty list, you can use Collections.EMPTY_LIST or emptyList().
If you want an unmodifiable List containing a single item, compare Collections.singletonlist("My Object") to the code doing the same.
 
Praveen Seluka
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for your answer david
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic