• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to ensure a set with only one element with capacity declared  RSS feed

 
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all, I have a question. Suppose I create a set with capacity 1. How can I restrict it so the set will only have 1 element at any one time without doing explicit checking for size or emptyness. I know I can do this will an array but I don't want to use an array.

 
Sheriff
Posts: 21137
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use Collections.singleton if you wouldn't need to change the single value.


You can always write your own Set subclass, wrapped around a single value:

But I do think that extending an existing Set implementation and overriding add and addAll will be a bit easier
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks rob for your input. I will think about it. I may switch back to an array if needed LOL
 
Rob Spoor
Sheriff
Posts: 21137
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To be honest, an array would be more useful. And should you need a Collection, you can use Arrays.asList which will wrap the array into a List.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!