• Post Reply Bookmark Topic Watch Topic
  • New Topic

cast a List to a Set  RSS feed

 
Larry Jones
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is it possible to cast a List to a Set?
for example,

List results = DbService.getList();
Set s = (Set) results;
 
Dave Wingate
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know of a way to do it with casting. But you can do the following since a List is a Collection

List list = someObject.getList();
Set set = new HashSet();
set.addAll(list);

Ithink this will get you what you wanted. Note that for this to work you need to make sure that the members of your list appropriately implement equals() and hashCode().
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Larry Jones:
is it possible to cast a List to a Set?
for example,

List results = DbService.getList();
Set s = (Set) results;


Only if the List object also implements the Set interface, which it most probably will not.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!