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

The following are Jave code examples for showing how to use binarySearch() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: MainCalendar   File: DatePicker.java   View Source Code Vote up 6 votes
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;
}
 
Example 2
Project: powertext   File: DefaultFoldManager.java   View Source Code Vote up 6 votes
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);
				}
			}
		}
	}
}
 
Example 3
Project: cas-5.1.0   File: SimpleHttpClient.java   View Source Code Vote up 6 votes
@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;
}
 
Example 4
Project: incubator-netbeans   File: AnnotationHolder.java   View Source Code Vote up 6 votes
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
        }
    }
}
 
Example 5
Project: DicomViewer   File: SortedListTools.java   View Source Code Vote up 6 votes
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;
}
 
Example 6
Project: incubator-netbeans   File: SortedListModel.java   View Source Code Vote up 5 votes
/**
 *
 */
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;
}
 
Example 7
Project: hadoop   File: AbstractINodeDiffList.java   View Source Code Vote up 5 votes
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};
}
 
Example 8
Project: OpenJSharp   File: Spans.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 9
Project: publicProject   File: ByteArrayPool.java   View Source Code Vote up 5 votes
/**
 * 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();
}
 
Example 10
Project: dremio-oss   File: NamespaceServiceImpl.java   View Source Code Vote up 5 votes
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;
}
 
Example 11
Project: airgram   File: ByteArrayPool.java   View Source Code Vote up 5 votes
/**
 * 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();
}
 
Example 12
Project: incubator-netbeans   File: CoverageHighlightsContainer.java   View Source Code Vote up 5 votes
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();
        }
    });
}
 
Example 13
Project: GitHub   File: Dex.java   View Source Code Vote up 4 votes
public int findStringIndex(String s) {
    return Collections.binarySearch(strings, s);
}
 
Example 14
Project: dxram   File: OverlaySuperpeer.java   View Source Code Vote up 4 votes
/**
 * 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 */
}
 
Example 15
Project: javaide   File: Dex.java   View Source Code Vote up 4 votes
public int findTypeIndex(String descriptor) {
    return Collections.binarySearch(typeNames, descriptor);
}
 
Example 16
Project: dxram   File: OverlayPeer.java   View Source Code Vote up 4 votes
/**
 * 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;
}
 
Example 17
Project: incubator-netbeans   File: SortedListModel.java   View Source Code Vote up 4 votes
/**
 *
 */
public int indexOf(Object o)
{
    return Collections.binarySearch(elements, o, getComparator());
}
 
Example 18
Project: InventoryPlus   File: Autocomplete.java   View Source Code Vote up 4 votes
@Override
public void insertUpdate(DocumentEvent ev) {
    if (ev.getLength() != 1)
        return;

    int pos = ev.getOffset();
    String content = null;
    try {
        content = textField.getText(0, pos + 1);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }

    // Find where the word starts
    int w;
    for (w = pos; w >= 0; w--) {
        if (!Character.isLetter(content.charAt(w))) {
            break;
        }
    }

    // Too few chars
    if (pos - w < 2)
        return;

    String prefix = content.substring(w + 1).toLowerCase();
    int n = Collections.binarySearch(keywords, prefix);
    if (n < 0 && -n <= keywords.size()) {
        String match = keywords.get(-n - 1);
        if (match.startsWith(prefix)) {
            // A completion is found
            String completion = match.substring(pos - w);
            // We cannot modify Document from within notification,
            // so we submit a task that does the change later
            SwingUtilities.invokeLater(new CompletionTask(completion, pos + 1));
        }
    } else {
        // Nothing found
        mode = Mode.INSERT;
    }
}
 
Example 19
Project: googles-monorepo-demo   File: Ordering.java   View Source Code Vote up 2 votes
/**
 * {@link Collections#binarySearch(List, Object, Comparator) Searches}
 * {@code sortedList} for {@code key} using the binary search algorithm. The
 * list must be sorted using this ordering.
 *
 * @param sortedList the list to be searched
 * @param key the key to be searched for
 * @deprecated Use {@link Collections#binarySearch(List, Object, Comparator)} directly. This
 * method is scheduled for deletion in June 2018.
 */
@Deprecated
public int binarySearch(List<? extends T> sortedList, @Nullable T key) {
  return Collections.binarySearch(sortedList, key, this);
}
 
Example 20
Project: s-store   File: Ordering.java   View Source Code Vote up 2 votes
/**
 * {@link Collections#binarySearch(List, Object, Comparator) Searches}
 * {@code sortedList} for {@code key} using the binary search algorithm. The
 * list must be sorted using this ordering.
 *
 * @param sortedList the list to be searched
 * @param key the key to be searched for
 */
public int binarySearch(List<? extends T> sortedList, @Nullable T key) {
  return Collections.binarySearch(sortedList, key, this);
}