WonderWoman
WonderWoman

Reputation: 164

Getting a closed interval subset for user defined classes in Java

As per Java API :

The following one-liner tells you how many words between "doorbell" and "pickle", including doorbell and pickle, are contained in the dictionary.

count = dictionary.subSet("doorbell", "pickle\0").size();

I understand that for a set of String elements, appending "\0" would work and for a set of Integer elements, using +1 would work.

If the set contains user defined objects, the subset() gives a half open range.

count = employee.subSet(obj1, obj6).size();

I was wondering if there is any possible way to get a closed range in this case.

Upvotes: 0

Views: 88

Answers (1)

Andy Turner
Andy Turner

Reputation: 140484

For a NavigableSet (e.g. a TreeSet), you could simply use the subSet overload which takes inclusivity parameters:

employee.subSet(obj1, true, obj6, true)

For a general SortedSet, the only ways you could do this are:

  1. Define some notion of constructing the Employee which is "just beyond" the upper bound.

    You could do this by knowing something of the internals of the class, e.g. if Employees are sorted by surname and your upper bound's surname were "Turner", you could construct an employee called "Turner\0".

  2. Do it "manually" by iterating the set:

    SortedSet<Employee> subset = employees.tailSet(obj1);
    for (Employee employee : subset) {
      if (employee.compareTo(obj6) < 0) {
        subset = subset.headSet(obj6);
        break;
      }
    }
    

Upvotes: 1

Related Questions