本文整理汇总了Java中java.util.Collections.binarySearch方法的典型用法代码示例。如果您正苦于以下问题:Java Collections.binarySearch方法的具体用法?Java Collections.binarySearch怎么用?Java Collections.binarySearch使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.Collections
的用法示例。
在下文中一共展示了Collections.binarySearch方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: isValidEndPoint
import java.util.Collections; //导入方法依赖的package包/类
@Override
public boolean isValidEndPoint(final URL url) {
Assert.notNull(this.httpClient);
HttpEntity entity = null;
try (CloseableHttpResponse response = this.httpClient.execute(new HttpGet(url.toURI()))) {
final int responseCode = response.getStatusLine().getStatusCode();
final int idx = Collections.binarySearch(this.acceptableCodes, responseCode);
if (idx >= 0) {
LOGGER.debug("Response code from server matched [{}].", responseCode);
return true;
}
LOGGER.debug("Response code did not match any of the acceptable response codes. Code returned was [{}]", responseCode);
if (responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
final String value = response.getStatusLine().getReasonPhrase();
LOGGER.error("There was an error contacting the endpoint: [{}]; The error was:\n[{}]", url.toExternalForm(), value);
}
entity = response.getEntity();
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
} finally {
EntityUtils.consumeQuietly(entity);
}
return false;
}
示例2: findItemIndex
import java.util.Collections; //导入方法依赖的package包/类
private int findItemIndex(ArrayList<String> items, int item) {
//折半查找有序元素的索引
int index = Collections.binarySearch(items, item, new Comparator<Object>() {
@Override
public int compare(Object lhs, Object rhs) {
String lhsStr = lhs.toString();
String rhsStr = rhs.toString();
lhsStr = lhsStr.startsWith("0") ? lhsStr.substring(1) : lhsStr;
rhsStr = rhsStr.startsWith("0") ? rhsStr.substring(1) : rhsStr;
return Integer.parseInt(lhsStr) - Integer.parseInt(rhsStr);
}
});
if (index < 0) {
index = 0;
}
return index;
}
示例3: keepFoldState
import java.util.Collections; //导入方法依赖的package包/类
private void keepFoldState(Fold newFold, List<Fold> oldFolds) {
int previousLoc = Collections.binarySearch(oldFolds, newFold);
//System.out.println(newFold + " => " + previousLoc);
if (previousLoc>=0) {
Fold prevFold = oldFolds.get(previousLoc);
newFold.setCollapsed(prevFold.isCollapsed());
}
else {
//previousLoc = -(insertion point) - 1;
int insertionPoint = -(previousLoc + 1);
if (insertionPoint>0) {
Fold possibleParentFold = oldFolds.get(insertionPoint-1);
if (possibleParentFold.containsOffset(
newFold.getStartOffset())) {
List<Fold> children = possibleParentFold.getChildren();
if (children!=null) {
keepFoldState(newFold, children);
}
}
}
}
}
示例4: findPositionGE
import java.util.Collections; //导入方法依赖的package包/类
private synchronized int findPositionGE(int offset) {
while (true) {
try {
int index = Collections.binarySearch(knownPositions, offset, new PositionComparator());
if (index >= 0) {
return index;
} else {
return - (index + 1);
}
} catch (Abort a) {
LOG.log(Level.FINE, "a null Position detected - clearing"); //NOI18N
int removedCount = 0;
for (Iterator<Reference<Position>> it = knownPositions.iterator(); it.hasNext(); ) {
if (it.next().get() == null) {
removedCount++;
it.remove();
}
}
LOG.log(Level.FINE, "clearing finished, {0} positions cleared", removedCount); //NOI18N
}
}
}
示例5: idOfPreviousOrEqual
import java.util.Collections; //导入方法依赖的package包/类
public static <T> Integer idOfPreviousOrEqual(final List<? extends Comparable<? super T>> list, final T key) {
if (list == null || list.isEmpty()) {
return null;
}
if (list.get(list.size() - 1).compareTo(key) <= 0) {
return list.size() - 1;
}
int idx = Collections.binarySearch(list, key);
if (idx < 0) {
idx = -(idx) - 1;
if (idx != 0 && idx < list.size()) {
return idx - 1;
}
return null;
}
return idx;
}
示例6: add
import java.util.Collections; //导入方法依赖的package包/类
/**
*
*/
public int add(Object o)
{
int index = Collections.binarySearch(elements, o, getComparator());
if (index < 0)
index = -index - 1;
elements.add(index, o);
fireIntervalAdded(this, index, index);
return index;
}
示例7: changedBetweenSnapshots
import java.util.Collections; //导入方法依赖的package包/类
final int[] changedBetweenSnapshots(Snapshot from, Snapshot to) {
Snapshot earlier = from;
Snapshot later = to;
if (Snapshot.ID_COMPARATOR.compare(from, to) > 0) {
earlier = to;
later = from;
}
final int size = diffs.size();
int earlierDiffIndex = Collections.binarySearch(diffs, earlier.getId());
int laterDiffIndex = later == null ? size : Collections
.binarySearch(diffs, later.getId());
if (-earlierDiffIndex - 1 == size) {
// if the earlierSnapshot is after the latest SnapshotDiff stored in
// diffs, no modification happened after the earlierSnapshot
return null;
}
if (laterDiffIndex == -1 || laterDiffIndex == 0) {
// if the laterSnapshot is the earliest SnapshotDiff stored in diffs, or
// before it, no modification happened before the laterSnapshot
return null;
}
earlierDiffIndex = earlierDiffIndex < 0 ? (-earlierDiffIndex - 1)
: earlierDiffIndex;
laterDiffIndex = laterDiffIndex < 0 ? (-laterDiffIndex - 1)
: laterDiffIndex;
return new int[]{earlierDiffIndex, laterDiffIndex};
}
示例8: intersects
import java.util.Collections; //导入方法依赖的package包/类
/**
* Returns true if the span defined by the half-open
* interval from <code>start</code> up to,
* but not including, <code>end</code> intersects
* any of the spans defined by this instance.
*/
public boolean intersects(float start, float end) {
boolean doesIntersect;
if (mSpans != null) {
/* If we have added any spans since we last
* sorted and collapsed our list of spans
* then we need to resort and collapse.
*/
if (mAddsSinceSort > 0) {
sortAndCollapse();
}
/* The SpanIntersection comparator considers
* two spans equal if they intersect. If
* the search finds a match then we have an
* intersection.
*/
int found = Collections.binarySearch(mSpans,
new Span(start, end),
SpanIntersection.instance);
doesIntersect = found >= 0;
/* The addInfinite() method has been invoked so
* everything intersect this instance.
*/
} else {
doesIntersect = true;
}
return doesIntersect;
}
示例9: returnBuf
import java.util.Collections; //导入方法依赖的package包/类
/**
* Returns a buffer to the pool, throwing away old buffers if the pool would exceed its allotted
* size.
*
* @param buf the buffer to return to the pool.
*/
public synchronized void returnBuf(byte[] buf) {
if (buf == null || buf.length > mSizeLimit) {
return;
}
mBuffersByLastUse.add(buf);
int pos = Collections.binarySearch(mBuffersBySize, buf, BUF_COMPARATOR);
if (pos < 0) {
pos = -pos - 1;
}
mBuffersBySize.add(pos, buf);
mCurrentSize += buf.length;
trim();
}
示例10: deleteSplitOrphans
import java.util.Collections; //导入方法依赖的package包/类
public int deleteSplitOrphans() {
final List<SplitRange> ranges = new ArrayList<>();
int itemsDeleted = 0;
for(Map.Entry<byte[], NameSpaceContainer> entry : namespace.find()) {
NameSpaceContainer container = entry.getValue();
if(container.getType() == Type.DATASET && container.getDataset().getReadDefinition() != null && container.getDataset().getReadDefinition().getSplitVersion() != null) {
ranges.add(new SplitRange(DatasetSplitId.getSplitStringRange(container.getDataset())));
}
}
for(Map.Entry<DatasetSplitId, DatasetSplit> e : splitsStore.find()) {
String id = e.getKey().getSplitIdentifier();
final int item = Collections.binarySearch(ranges, new SplitRange(Range.singleton(id)));
// we should never find a match since we're searching for a split key.
Preconditions.checkArgument(item < 0);
final int insertionPoint = (-item) - 1;
final int consideredRange = insertionPoint - 1; // since a normal match would come directly after the start range, we need to check the range directly above the insertion point.
if(consideredRange < 0 || ranges.get(consideredRange).range.contains(id)) {
splitsStore.delete(e.getKey());
itemsDeleted++;
}
}
return itemsDeleted;
}
示例11: findPositionIndex
import java.util.Collections; //导入方法依赖的package包/类
private int findPositionIndex(List<Position> positions, final int target) {
return Collections.binarySearch(positions, new Position() {
public int getOffset() {
return target;
}
}, new Comparator<Position>() {
public int compare(Position pos1, Position pos2) {
return pos1.getOffset() - pos2.getOffset();
}
});
}
示例12: findStringIndex
import java.util.Collections; //导入方法依赖的package包/类
public int findStringIndex(String s) {
return Collections.binarySearch(strings, s);
}
示例13: spreadBackupsOfThisSuperpeer
import java.util.Collections; //导入方法依赖的package包/类
/**
* Spread backups of failed superpeer
*
* @param p_lastBackupSuperpeer
* the last backup superpeer
* @lock overlay lock must be read-locked
*/
private void spreadBackupsOfThisSuperpeer(final short p_lastBackupSuperpeer) {
short newBackupSuperpeer;
int index;
boolean superpeerToSendData = false;
byte[] metadata;
String str = "Spreaded data of ";
metadata = m_metadata.receiveMetadataInRange(m_predecessor, m_nodeID);
while (!m_superpeers.isEmpty()) {
// Determine successor of last backup superpeer
index = (short) Collections.binarySearch(m_superpeers, (short) (p_lastBackupSuperpeer + 1));
if (index < 0) {
index = index * -1 - 1;
if (index == m_superpeers.size()) {
index = 0;
}
}
newBackupSuperpeer = m_superpeers.get(index);
superpeerToSendData = true;
str += " to " + NodeID.toHexString(newBackupSuperpeer);
try {
m_network.sendMessage(new SendBackupsMessage(newBackupSuperpeer, metadata));
} catch (final NetworkException e) {
// Superpeer is not available anymore, remove from superpeer array and try next superpeer
// #if LOGGER >= ERROR
LOGGER.error("new backup superpeer (0x%X) failed, too", newBackupSuperpeer);
// #endif /* LOGGER >= ERROR */
continue;
}
break;
}
// #if LOGGER >= DEBUG
if (metadata.length > 0 && superpeerToSendData) {
LOGGER.debug(str);
} else {
LOGGER.debug("No need to spread data");
}
// #endif /* LOGGER >= DEBUG */
}
示例14: findTypeIndex
import java.util.Collections; //导入方法依赖的package包/类
public int findTypeIndex(String descriptor) {
return Collections.binarySearch(typeNames, descriptor);
}
示例15: getResponsibleSuperpeer
import java.util.Collections; //导入方法依赖的package包/类
/**
* Determines the responsible superpeer for given NodeID
*
* @param p_nodeID
* NodeID from chunk whose location is searched
* @param p_check
* whether the result has to be checked (in case of incomplete superpeer overlay) or not
* @return the responsible superpeer for given ChunkID
* @lock overlay lock must be read-locked
*/
private short getResponsibleSuperpeer(final short p_nodeID, final boolean p_check) {
short responsibleSuperpeer = NodeID.INVALID_ID;
short predecessor;
short hisSuccessor;
int index;
AskAboutSuccessorRequest request;
AskAboutSuccessorResponse response;
// #if LOGGER == TRACE
LOGGER.trace("Entering getResponsibleSuperpeer with: p_nodeID=0x%X", p_nodeID);
// #endif /* LOGGER == TRACE */
if (!m_superpeers.isEmpty()) {
index = Collections.binarySearch(m_superpeers, p_nodeID);
if (index < 0) {
index = index * -1 - 1;
if (index == m_superpeers.size()) {
index = 0;
}
}
responsibleSuperpeer = m_superpeers.get(index);
if (p_check && m_superpeers.size() > 1) {
if (index == 0) {
index = m_superpeers.size() - 1;
} else {
index--;
}
predecessor = m_superpeers.get(index);
while (true) {
m_overlayLock.readLock().unlock();
request = new AskAboutSuccessorRequest(predecessor);
try {
m_network.sendSync(request);
} catch (final NetworkException e) {
// Predecessor is not available, try responsibleSuperpeer without checking
m_overlayLock.readLock().lock();
break;
}
m_overlayLock.readLock().lock();
response = request.getResponse(AskAboutSuccessorResponse.class);
hisSuccessor = response.getSuccessor();
if (responsibleSuperpeer == hisSuccessor) {
break;
} else if (OverlayHelper.isSuperpeerInRange(p_nodeID, predecessor, hisSuccessor)) {
responsibleSuperpeer = hisSuccessor;
break;
} else {
predecessor = hisSuccessor;
}
}
}
} else {
// #if LOGGER >= WARN
LOGGER.warn("Do not know any superpeer");
// #endif /* LOGGER >= WARN */
}
// #if LOGGER == TRACE
LOGGER.trace("Exiting getResponsibleSuperpeer");
// #endif /* LOGGER == TRACE */
return responsibleSuperpeer;
}