private BitRange findOrCreateRange(int index, boolean create) {
        // In many cases a bit from the last accessed range
        // is requested and no further search is required.
        if((lastRange != null) && indexInRange(index, lastRange)) {
            return lastRange;
        }

        int groupIndex = index / BITS_PER_GROUP;
        BitRange range = ranges.get(groupIndex);
        BitRange previousRange = range;

        while((range != null) && (index >= range.startIndex)) {
            if(indexInRange(index, range)) {
                // Found the range containing the index.
                lastRange = range;
                return range;
            }

            previousRange = range;
            range = range.next;
        }

        if(!create) {
            return null;
        }

        // Create a new range containing the given index.
        int startIndex = index - (index % BITS_PER_RANGE);
        BitRange newRange = new BitRange(startIndex);

        if(previousRange == null) {
            // The first range in this group.
            ranges.put(groupIndex, newRange);
        }
        else if(index > previousRange.startIndex) {
            // A new range must be created after the last one.
            newRange.next = previousRange.next;
            previousRange.next = newRange;
        }
        else {
            // A new range must be created before the last one
            // and it replaces the group representative.
            newRange.next = previousRange;
            ranges.put(groupIndex, newRange);
        }

        lastRange = newRange;
        return newRange;
    }