Java Code Examples for java.util.Collections#binarySearch()

The following examples show how to use java.util.Collections#binarySearch() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: big-c   File: AbstractINodeDiffList.java    License: Apache License 2.0 6 votes vote down vote up
public final D getDiffById(final int snapshotId) {
  if (snapshotId == Snapshot.CURRENT_STATE_ID) {
    return null;
  }
  final int i = Collections.binarySearch(diffs, snapshotId);
  if (i >= 0) {
    // exact match
    return diffs.get(i);
  } else {
    // Exact match not found means that there were no changes between
    // given snapshot and the next state so that the diff for the given
    // snapshot was not recorded. Thus, return the next state.
    final int j = -i - 1;
    return j < diffs.size()? diffs.get(j): null;
  }
}
 
Example 2
Source Project: uima-uimaj   File: Subiterator.java    License: Apache License 2.0 6 votes vote down vote up
@Override  
public void moveToPreviousNvc() {    
  // no isValid check because caller checked: "Nvc"
  if (isListForm) {
    --this.pos;
    return;
  }
  
  if (isUnambiguous) {
    // Convert to list form
    Annotation currentAnnotation = it.getNvc();  // save to restore position
    convertToListForm();
    pos = Collections.binarySearch(this.list, currentAnnotation, annotationComparator_withId);
    --this.pos;
    return;
  }

  // is ambiguous, not list form
  maybeMoveToPrevBounded();  // makes iterator invalid if moving before startId 

  adjustForStrictOrCoveringAndBoundSkip_backwards();
}
 
Example 3
Source Project: coming   File: Nopol2017_002_s.java    License: MIT License 6 votes vote down vote up
/**
 * Updates (changes) the value for a time period.  Throws a 
 * {@link SeriesException} if the period does not exist.
 *
 * @param period  the period (<code>null</code> not permitted).
 * @param value  the value (<code>null</code> permitted).
 */
public void update(RegularTimePeriod period, Number value) {
    TimeSeriesDataItem temp = new TimeSeriesDataItem(period, value);
    int index = Collections.binarySearch(this.data, temp);
    if (index >= 0) {
        TimeSeriesDataItem pair = (TimeSeriesDataItem) this.data.get(index);
        pair.setValue(value);
        fireSeriesChanged();
    }
    else {
        throw new SeriesException(
            "TimeSeries.update(TimePeriod, Number):  period does not exist."
        );
    }

}
 
Example 4
Source Project: opensim-gui   File: TimeSeries.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the data item for a specific period.
 *
 * @param period  the period of interest (<code>null</code> not allowed).
 *
 * @return The data item matching the specified period (or 
 *         <code>null</code> if there is no match).
 *
 * @see #getDataItem(int)
 */
public TimeSeriesDataItem getDataItem(RegularTimePeriod period) {
    if (period == null) {
        throw new IllegalArgumentException("Null 'period' argument");
    }
    TimeSeriesDataItem dummy = new TimeSeriesDataItem(period, 
            Integer.MIN_VALUE);
    int index = Collections.binarySearch(this.data, dummy);
    if (index >= 0) {
        return (TimeSeriesDataItem) this.data.get(index);
    }
    else {
        return null;
    }
}
 
Example 5
Source Project: Indic-Keyboard   File: SparseArray.java    License: Apache License 2.0 5 votes vote down vote up
public E get(final int key, final E valueIfKeyNotFound) {
    final int index = Collections.binarySearch(mKeys, key);
    if (index >= 0) {
        return mValues.get(index);
    }
    return valueIfKeyNotFound;
}
 
Example 6
/**
 * Updates (changes) the value for a time period.  Throws a
 * {@link SeriesException} if the period does not exist.
 *
 * @param period  the period (<code>null</code> not permitted).
 * @param value  the value (<code>null</code> permitted).
 */
public void update(RegularTimePeriod period, Number value) {
    TimeSeriesDataItem temp = new TimeSeriesDataItem(period, value);
    int index = Collections.binarySearch(this.data, temp);
    if (index < 0) {
        throw new SeriesException("There is no existing value for the "
                + "specified 'period'.");
    }
    update(index, value);
}
 
Example 7
/**
 * Returns the row index for a given key.
 *
 * @param key  the key (<code>null</code> not permitted).
 *
 * @return The row index.
 *
 * @see #getRowKey(int)
 * @see #getColumnIndex(Comparable)
 */
@Override
public int getRowIndex(Comparable key) {
    ParamChecks.nullNotPermitted(key, "key");
    if (this.sortRowKeys) {
        return Collections.binarySearch(this.rowKeys, key);
    }
    else {
        return this.rowKeys.indexOf(key);
    }
}
 
Example 8
Source Project: astor   File: TimeSeries.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds or updates an item in the times series and sends a 
 * {@link org.jfree.data.general.SeriesChangeEvent} to all registered 
 * listeners.
 *
 * @param period  the time period to add/update (<code>null</code> not 
 *                permitted).
 * @param value  the new value (<code>null</code> permitted).
 *
 * @return A copy of the overwritten data item, or <code>null</code> if no 
 *         item was overwritten.
 */
public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, 
                                      Number value) {

    if (period == null) {
        throw new IllegalArgumentException("Null 'period' argument.");   
    }
    TimeSeriesDataItem overwritten = null;

    TimeSeriesDataItem key = new TimeSeriesDataItem(period, value);
    int index = Collections.binarySearch(this.data, key);
    if (index >= 0) {
        TimeSeriesDataItem existing 
            = (TimeSeriesDataItem) this.data.get(index);
        overwritten = (TimeSeriesDataItem) existing.clone();
        existing.setValue(value);
        removeAgedItems(false);  // remove old items if necessary, but
                                 // don't notify anyone, because that
                                 // happens next anyway...
        fireSeriesChanged();
    }
    else {
        this.data.add(-index - 1, new TimeSeriesDataItem(period, value));

        // check if this addition will exceed the maximum item count...
        if (getItemCount() > this.maximumItemCount) {
            this.data.remove(0);
        }

        removeAgedItems(false);  // remove old items if necessary, but
                                 // don't notify anyone, because that
                                 // happens next anyway...
        fireSeriesChanged();
    }
    return overwritten;

}
 
Example 9
Source Project: coming   File: Cardumen_004_t.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the index for the item (if any) that corresponds to a time 
 * period.
 *
 * @param period  the time period (<code>null</code> not permitted).
 *
 * @return The index.
 */
public int getIndex(RegularTimePeriod period) {
    if (period == null) {
        throw new IllegalArgumentException("Null 'period' argument.");
    } 
    TimeSeriesDataItem dummy = new TimeSeriesDataItem(
          period, Integer.MIN_VALUE);
    return Collections.binarySearch(this.data, dummy);
}
 
Example 10
Source Project: coming   File: Cardumen_00145_t.java    License: MIT License 5 votes vote down vote up
/**
 * Returns the index for the item (if any) that corresponds to a time
 * period.
 *
 * @param period  the time period (<code>null</code> not permitted).
 *
 * @return The index.
 */
public int getIndex(RegularTimePeriod period) {
    if (period == null) {
        throw new IllegalArgumentException("Null 'period' argument.");
    }
    TimeSeriesDataItem dummy = new TimeSeriesDataItem(
          period, Integer.MIN_VALUE);
    return Collections.binarySearch(this.data, dummy);
}
 
Example 11
@SuppressWarnings("unchecked")
@TLFunctionAnnotation("Searches a list for the specified value. The list must be sorted in ascending order.")
public static final <V> Integer binarySearch(TLFunctionCallContext context, List<V> list, V value) {
	if (value == null) {
		throw new NullPointerException("value is null");
	} else if (!(value instanceof Comparable)) {
		throw new IllegalArgumentException("value is not comparable");
	}
	return Collections.binarySearch(((List<? extends Comparable<? super V>>) list), value);
}
 
Example 12
Source Project: stratio-cassandra   File: IndexHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * The index of the IndexInfo in which a scan starting with @name should begin.
 *
 * @param name
 *         name of the index
 *
 * @param indexList
 *          list of the indexInfo objects
 *
 * @param comparator
 *          comparator type
 *
 * @param reversed
 *          is name reversed
 *
 * @return int index
 */
public static int indexFor(Composite name, List<IndexInfo> indexList, CType comparator, boolean reversed, int lastIndex)
{
    if (name.isEmpty())
        return lastIndex >= 0 ? lastIndex : reversed ? indexList.size() - 1 : 0;

    if (lastIndex >= indexList.size())
        return -1;

    IndexInfo target = new IndexInfo(name, name, 0, 0);
    /*
    Take the example from the unit test, and say your index looks like this:
    [0..5][10..15][20..25]
    and you look for the slice [13..17].

    When doing forward slice, we we doing a binary search comparing 13 (the start of the query)
    to the lastName part of the index slot. You'll end up with the "first" slot, going from left to right,
    that may contain the start.

    When doing a reverse slice, we do the same thing, only using as a start column the end of the query,
    i.e. 17 in this example, compared to the firstName part of the index slots.  bsearch will give us the
    first slot where firstName > start ([20..25] here), so we subtract an extra one to get the slot just before.
    */
    int startIdx = 0;
    List<IndexInfo> toSearch = indexList;
    if (lastIndex >= 0)
    {
        if (reversed)
        {
            toSearch = indexList.subList(0, lastIndex + 1);
        }
        else
        {
            startIdx = lastIndex;
            toSearch = indexList.subList(lastIndex, indexList.size());
        }
    }
    int index = Collections.binarySearch(toSearch, target, getComparator(comparator, reversed));
    return startIdx + (index < 0 ? -index - (reversed ? 2 : 1) : index);
}
 
Example 13
/**
 * Returns a tick unit that is larger than the supplied unit.
 *
 * @param unit   the unit.
 *
 * @return A tick unit that is larger than the supplied unit.
 */
@Override
public TickUnit getLargerTickUnit(TickUnit unit) {
    int index = Collections.binarySearch(this.tickUnits, unit);
    if (index >= 0) {
        index = index + 1;
    }
    else {
        index = -index;
    }

    return (TickUnit) this.tickUnits.get(Math.min(index,
            this.tickUnits.size() - 1));
}
 
Example 14
Source Project: hadoop   File: AclTransformation.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the entry matching the given key or null if not found.  An ACL
 * entry's key consists of scope, type and name (but not permission).
 *
 * @param key AclEntry search key
 * @return AclEntry entry matching the given key or null if not found
 */
public AclEntry findByKey(AclEntry key) {
  int index = Collections.binarySearch(aclSpec, key, ACL_ENTRY_COMPARATOR);
  if (index >= 0) {
    return aclSpec.get(index);
  }
  return null;
}
 
Example 15
Source Project: kylin   File: AclRecord.java    License: Apache License 2.0 5 votes vote down vote up
public Permission getPermission(Sid sid) {
    synchronized (entries) {
        int p = Collections.binarySearch(entries, new AceImpl(sid, null), AceImpl.SID_ORDER);
        if (p >= 0) {
            return entries.get(p).getPermission();
        }
        return null;
    }
}
 
Example 16
Source Project: MediaSDK   File: Util.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns the index of the largest element in {@code list} that is less than (or optionally equal
 * to) a specified {@code value}.
 *
 * <p>The search is performed using a binary search algorithm, so the list must be sorted. If the
 * list contains multiple elements equal to {@code value} and {@code inclusive} is true, the index
 * of the first one will be returned.
 *
 * @param <T> The type of values being searched.
 * @param list The list to search.
 * @param value The value being searched for.
 * @param inclusive If the value is present in the list, whether to return the corresponding
 *     index. If false then the returned index corresponds to the largest element strictly less
 *     than the value.
 * @param stayInBounds If true, then 0 will be returned in the case that the value is smaller than
 *     the smallest element in the list. If false then -1 will be returned.
 * @return The index of the largest element in {@code list} that is less than (or optionally equal
 *     to) {@code value}.
 */
public static <T extends Comparable<? super T>> int binarySearchFloor(
    List<? extends Comparable<? super T>> list,
    T value,
    boolean inclusive,
    boolean stayInBounds) {
  int index = Collections.binarySearch(list, value);
  if (index < 0) {
    index = -(index + 2);
  } else {
    while (--index >= 0 && list.get(index).compareTo(value) == 0) {}
    if (inclusive) {
      index++;
    }
  }
  return stayInBounds ? Math.max(0, index) : index;
}
 
Example 17
Source Project: kylin   File: SparkCubeHFile.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public int getPartition(Object o) {
    int pos = Collections.binarySearch(this.keys, (RowKeyWritable) o) + 1;
    return pos < 0 ? -pos : pos;
}
 
Example 18
private int unsafeBinarySearch(Object key) throws ClassCastException {
  return Collections.binarySearch(elements, key, unsafeComparator());
}
 
Example 19
Source Project: RxTools-master   File: RxSeatMovie.java    License: Apache License 2.0 4 votes vote down vote up
private int isHave(Integer seat) {
    return Collections.binarySearch(selects, seat);
}
 
Example 20
Source Project: Wurst7   File: XRayHack.java    License: GNU General Public License v3.0 4 votes vote down vote up
private boolean isVisible(Block block)
{
	String name = BlockUtils.getName(block);
	int index = Collections.binarySearch(oreNames, name);
	return index >= 0;
}