This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes Java in General and the fly likes singletonXXX( )   methods in java.util.Collections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "singletonXXX( )   methods in java.util.Collections" Watch "singletonXXX( )   methods in java.util.Collections" New topic

singletonXXX( ) methods in java.util.Collections

Yan Lee
Ranch Hand

Joined: Sep 15, 2003
Posts: 94
Hi all:
I am trying to understand the following methods in the java.util.Collections class:
Can you tell me under what circumstances does one use these methods and why would one use them?
static Set singleton(Object o)
Returns an immutable set containing only the specified object.
static List singletonList(Object o)
Returns an immutable list containing only the specified object.
static Map singletonMap(Object key, Object value)
Returns an immutable map, mapping only the specified key to the specified value.
Thanks in advance for the help.
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
I think they are just convenience methods, as stated in Sun's Collections tutorial.
So if you have a single object and you need to pass it to a method that takes a "java.util.List", this saves you from creating the List and adding the object to it. It's not a big savings [one statement instead of two], but so be it.
It is sorta covered in the JavaRanch Style Guide.
subject: singletonXXX( ) methods in java.util.Collections
jQuery in Action, 3rd edition