There can be many solutions, how to organize better - in general, it cannot be said, since the criteria for "best" may be different. One of the possible solutions (the first one that came to mind) is to represent occupied ranges as pairs of numbers '[beginning of range, end of range]', for example Map.Entry<Double, Double> and store them in an ordered dictionary, you can in 'TreeMap'.
In this case, the code for reserving the range may be something like this:
Map.Entry<Double, Double> occupy(Double rangeStart, Double rangeEnd) { Map.Entry<Double, Double> floor = map.floorEntry(rangeStart); if (floor != null && floor.getValue() >= rangeStart) { map.remove(floor.getKey()); rangeStart = Math.min(floor.getKey(), rangeStart); rangeEnd = Math.max(floor.getValue(), rangeEnd); } Map.Entry<Double, Double> ceiling = map.ceilingEntry(rangeStart); if (ceiling != null && ceiling.getKey() <= rangeEnd) { map.remove(ceiling.getKey()); rangeEnd = Math.max(ceiling.getValue(), rangeEnd); } map.put(rangeStart, rangeEnd); return map.ceilingEntry(rangeStart); }
And the code to check whether the range you are interested in is busy or not. It may look something like this:
/** Checks if the whole range is occupied -- no free areas */ boolean isFree(Double rangeStart, Double rangeEnd) { Map.Entry<Double, Double> floor = map.floorEntry(rangeStart); if (floor != null && floor.getValue() >= rangeStart) return false; Map.Entry<Double, Double> ceiling = map.ceilingEntry(rangeStart); if (ceiling != null && ceiling.getKey() <= rangeEnd) return false; return true; } /** Checks if the whole range is free -- no occupied areas */ boolean isOccupied(Double rangeStart, Double rangeEnd) { Map.Entry<Double, Double> floor = map.floorEntry(rangeStart); if (floor != null && floor.getValue() >= rangeEnd) return true; return false; }
A working snippet with a couple of additional methods and a minimalist test suite can be found at http://ideone.com/3arRnM . I cannot vouch for the loyalty and beauty of the code - the idea is not very thought out and implemented hastily. Think, induce beauty and test further yourself.