Search code examples
javaoopcollections

LinkedHashSet as a returning type of API public method


Let's consider the following example.

Writing API which has public method which returns Collection of unique Objects. I believe that is is good to write return type of that method Set to show to user that the items are unique. In case when these items are unique and ordered is it a right idea to write return type LinkedHashSet or it is good to be Collection?

I know collections which are unique and sorted. I what to know it is a good idea to set public method's return type class(TreeSet,SortedSet,LinkedHashSet). In in terms of oop.


Solution

  • I'd recommend against returning LinkedHashSet (unless you have a very good justification for it). If you return Set, you can change the Set implementation as you see fit, e.g. HashSet, TreeSet etc

    In this case, I think your suggestion of returning Set is a good one as it does indicate that the items are unique. This also indicates that contains will generally be fast (O(1) or O(log n)).

    On the other hand, Collection is very generic, but all it tells the caller is that it is a plain old group of somethings without any special constraints on ordering or uniqueness. Specifying Set means that there isn't any confusion about uniqueness, and you can use it anywhere where a Collection can be used anyway.