下面列出了java.util.Queue#isEmpty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 获取当前匹配树存在的匹配资源(URL+METHOD)数量
* @return int 资源数量
*/
public int getResourceNum() {
int resourceNum = 0;
// 广度层级遍历
Queue<Node> resourceList = new LinkedList<>();
resourceList.add(root);
while (!resourceList.isEmpty()) {
Node currentNode = resourceList.poll();
if (NODE_TYPE_METHOD.equals(currentNode.nodeType)) {
resourceNum ++;
}
if (currentNode.getChildren() != null && !currentNode.getChildren().isEmpty()) {
resourceList.addAll(currentNode.getChildren().values());
}
}
if (logger.isDebugEnabled()) {
logger.debug("sureness - current PathTree resource num is: {}", resourceNum);
}
return resourceNum;
}
private void bfs(Graph G, int s) {
Queue<Integer> q = (Queue<Integer>) new LinkedList<Integer>();
q.add(s);
while (!q.isEmpty()) {
int v = q.poll();
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) {
marked[w] = true;
edgeTo[w] = v;
q.add(w);
}
}
}
}
public static void exit(final Throwable thrown) {
final Queue<Span> spans = spanHolder.get();
if (spans.isEmpty())
return;
final Span span = spans.poll();
if (thrown != null) {
span.log(errorLogs(thrown));
span.setTag(TAGS_KEY_ERROR, true);
span.setTag(TAGS_KEY_ERROR_MESSAGE, thrown.getMessage());
span.setTag(TAGS_KEY_HTTP_STATUS_CODE, 500);
}
else {
span.setTag(TAGS_KEY_HTTP_STATUS_CODE, 200);
}
span.finish();
}
void printLevelOrder(Node root) {
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while (!queue.isEmpty()) {
/* poll() removes the present head.
For more information on poll() visit
http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */
Node tempNode = queue.poll();
System.out.print(tempNode.data + " ");
/*Enqueue left child */
if (tempNode.left != null) {
queue.add(tempNode.left);
}
/*Enqueue right child */
if (tempNode.right != null) {
queue.add(tempNode.right);
}
}
}
private int drawStripesEndingBefore(int ys, @Nonnull Queue<PositionedStripe> ends, @Nonnull List<PositionedStripe> stripes, @Nonnull Graphics g, int yStart) {
while (!ends.isEmpty()) {
PositionedStripe endingStripe = ends.peek();
if (endingStripe.yEnd > ys) break;
ends.remove();
// check whether endingStripe got obscured in the range yStart..endingStripe.yEnd
int i = stripes.indexOf(endingStripe);
stripes.remove(i);
if (i == 0) {
// visible
drawSpot(g, endingStripe.thin, yStart, endingStripe.yEnd, endingStripe.color);
yStart = endingStripe.yEnd;
}
}
return yStart;
}
private void addScopeAndAncestorsToScopeMap(Map<S, ScopeWrapper<S>> scopeMap, ScopeWrapper<S> scope) {
if (scope == null) {
return;
}
Queue<ScopeWrapper<S>> ancestors = new LinkedList<>();
ancestors.add(scope);
while (!ancestors.isEmpty()) {
ScopeWrapper<S> thisScope = ancestors.poll();
if (!scopeMap.containsKey(thisScope.getType())) {
scopeMap.put(thisScope.getType(), thisScope);
} else if (!scopeMap.get(thisScope.getType()).equals(thisScope)) {
throw new IllegalStateException(String.format("Multiple scopes found with type %s but different identity: %s and %s.",
thisScope.getType(), thisScope.getScope(), scopeMap.get(thisScope.getType()).getScope()));
}
ancestors.addAll(thisScope.getParentScopes());
}
}
@Override
public void breadthFirstSearch(Task root, Predicate<Pair<Task, Task>> predicate) {
Preconditions.checkNotNull(root);
Queue<Task> queue = Queues.newArrayDeque();
if (predicate.apply(Pair.create((Task) null, root))) {
queue.add(root);
}
while (!queue.isEmpty()) {
Task head = queue.poll();
for (Task child : head.getNestedTasks()) {
if (predicate.apply(Pair.create(head, child))) {
queue.add(child);
}
}
}
}
private void indexString(Queue<Character> charSequence, int depth) {
if(charSequence.isEmpty()) {
Preconditions.checkArgument(!(isRoot() && depth == 0), "Empty string is not a valid prefix");
this.validPrefix = true;
} else {
Character c = charSequence.poll();
Node childNode;
if(children.containsKey(c))
childNode = children.get(c);
else {
childNode = new Node(c);
childNode.parent = this;
children.put(c, childNode);
}
childNode.indexString(charSequence, depth + 1);
}
}
public static void levelOrder(Node root)
{
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty())
{
Node curr = queue.remove();
System.out.print(" "+curr.data);
if (curr.left != null)
queue.add(curr.left);
if (curr.right != null)
queue.add(curr.right);
}
}
public void resend(String name, Queue<PushNotification> queue) {
IApnsService service = ApnsServiceImpl.getCachedService(name);
if (service != null) {
while (!queue.isEmpty()) {
service.sendNotification(queue.poll());
}
} else {
logger.error("Cached service is null. name: " + name);
}
}
@Override
public void handleSplitsChanges(Queue<SplitsChange<MockSourceSplit>> splitsChanges) {
do {
SplitsChange<MockSourceSplit> splitsChange = splitsChanges.poll();
if (splitsChange instanceof SplitsAddition) {
splitsChange.splits().forEach(s -> splits.put(s.splitId(), s));
}
} while (handleSplitsInOneShot && !splitsChanges.isEmpty());
}
/**
* A deserialized serialized deque has same elements in same order
*/
public void testSerialization() throws Exception {
Queue x = populatedDeque(SIZE);
Queue y = serialClone(x);
assertNotSame(y, x);
assertEquals(x.size(), y.size());
assertEquals(x.toString(), y.toString());
assertTrue(Arrays.equals(x.toArray(), y.toArray()));
while (!x.isEmpty()) {
assertFalse(y.isEmpty());
assertEquals(x.remove(), y.remove());
}
assertTrue(y.isEmpty());
}
/**
* Delete a storage group
*/
List<MeasurementMNode> deleteStorageGroup(String path) throws MetadataException {
MNode cur = getNodeByPath(path);
if (!(cur instanceof StorageGroupMNode)) {
throw new StorageGroupNotSetException(path);
}
// Suppose current system has root.a.b.sg1, root.a.sg2, and delete root.a.b.sg1
// delete the storage group node sg1
cur.getParent().deleteChild(cur.getName());
// collect all the LeafMNode in this storage group
List<MeasurementMNode> leafMNodes = new LinkedList<>();
Queue<MNode> queue = new LinkedList<>();
queue.add(cur);
while (!queue.isEmpty()) {
MNode node = queue.poll();
for (MNode child : node.getChildren().values()) {
if (child instanceof MeasurementMNode) {
leafMNodes.add((MeasurementMNode) child);
} else {
queue.add(child);
}
}
}
cur = cur.getParent();
// delete node b while retain root.a.sg2
while (!IoTDBConstant.PATH_ROOT.equals(cur.getName()) && cur.getChildren().size() == 0) {
cur.getParent().deleteChild(cur.getName());
cur = cur.getParent();
}
return leafMNodes;
}
@Override
public void deleteFolder(final Repository repository,
final String treePath,
final DateTime timestamp,
final BooleanSupplier cancelledCheck)
{
boolean canDeleteComponent =
securityHelper.isPermitted(new RepositoryViewPermission(repository, BreadActions.DELETE))[0];
ComponentMaintenance componentMaintenance = repository.facet(ComponentMaintenance.class);
Queue<String> paths = new PriorityQueue<>();
paths.add(treePath);
while (!cancelledCheck.getAsBoolean() && !paths.isEmpty()) {
String basePath = paths.poll();
List<String> path = Arrays.asList(basePath.split("/"));
Iterable<BrowseNode<EntityId>> nodes =
browseNodeStore.getByPath(repository.getName(), path, configuration.getMaxNodes());
Iterator<BrowseNode<EntityId>> nodeIterator = nodes.iterator();
while (!cancelledCheck.getAsBoolean() && nodeIterator.hasNext()) {
BrowseNode<EntityId> node = nodeIterator.next();
if (!node.isLeaf()) {
paths.offer(basePath + "/" + node.getName());
}
else if (canDeleteComponent && node.getAssetId() == null && node.getComponentId() != null) {
deleteComponent(repository, node.getComponentId(), timestamp, componentMaintenance);
}
if (node.getAssetId() != null) {
deleteAsset(repository, node.getAssetId(), timestamp, componentMaintenance);
}
}
}
}
private RecyclerView.ViewHolder getChildViewHolder(int viewType, ViewGroup parent) {
final Queue<RecyclerView.ViewHolder> viewHolders = childViewHolderCache.get(viewType);
if (!viewHolders.isEmpty()) {
return viewHolders.poll();
}
RecyclerView.ViewHolder childViewHolder = childAdapterViewTypeDelegates.get(viewType).createViewHolder(parent);
childViewHolder.itemView.setTag(new ChildViewState());
return childViewHolder;
}
/**
* Calls {@link ConfigConstraints#assertValid(Entity)} on the given entity and all of
* its descendants.
*/
private void validateDescendantConfig(Entity e) {
Queue<Entity> queue = Lists.newLinkedList();
queue.add(e);
while (!queue.isEmpty()) {
Entity e1 = queue.poll();
ConfigConstraints.assertValid(e1);
queue.addAll(e1.getChildren());
}
}
/**
* 判断是否为完全二叉树
*/
public static boolean isCBT(Node head) {
if (head == null) {
return true;
}
Queue<Node> queue = new LinkedList<Node>();
boolean leaf = false;
Node left = null;
Node right = null;
queue.offer(head);
while (!queue.isEmpty()) {
head = queue.poll();
left = head.left;
right = head.right;
// 有右孩子没有左孩子一定不是;如果两个孩子都没有,该结点下面结点必须是叶子结点;有左孩子没有右孩子则下面所有节点都是叶子节点。
if ((leaf && (left != null || right != null)) || (left == null && right != null)) {
return false;
}
if (left != null) {
queue.offer(left);
}
if (right != null) {
queue.offer(right);
} else {
// 左等于空或者右等于空 则开启。因为上面代码已经去掉左等于空的情况,因此这里只需要判断右是否为空;
leaf = true;
}
}
return true;
}
protected final CircularElement<E> takeNext(BlockingQueue<CircularElement<E>> queue, Queue<CircularElement<E>> cache)
throws InterruptedException {
return cache.isEmpty() ? queue.take() : cache.poll();
}
/**
* Converts a function call with a Union type input into a case statement, where each branch of the case corresponds to
* one of the subtypes of the Union type. The function call is materialized in each of the branches, with the union input cast
* to the specific type corresponding to the branch of the case statement
* @param call
* @param functionLookupContext
* @return
*/
private LogicalExpression rewriteUnionFunction(FunctionCall call, FunctionLookupContext functionLookupContext) {
LogicalExpression[] args = new LogicalExpression[call.args.size()];
call.args.toArray(args);
for (int i = 0; i < args.length; i++) {
LogicalExpression arg = call.args.get(i);
MajorType majorType = arg.getMajorType();
if (majorType.getMinorType() != MinorType.UNION) {
continue;
}
List<MinorType> subTypes = majorType.getSubTypeList();
Preconditions.checkState(subTypes.size() > 0, "Union type has no subtypes");
Queue<IfCondition> ifConditions = Lists.newLinkedList();
for (MinorType minorType : subTypes) {
LogicalExpression ifCondition = getIsTypeExpressionForType(minorType, arg.accept(new CloneVisitor(), null));
args[i] = getUnionAssertFunctionForType(minorType, arg.accept(new CloneVisitor(), null));
List<LogicalExpression> newArgs = Lists.newArrayList();
for (LogicalExpression e : args) {
newArgs.add(e.accept(new CloneVisitor(), null));
}
// When expanding the expression tree to handle the different subtypes, we will not throw an exception if one
// of the branches fails to find a function match, since it is possible that code path will never occur in execution
// So instead of failing to materialize, we generate code to throw the exception during execution if that code
// path is hit.
errorCollectors.push(errorCollector);
errorCollector = new ErrorCollectorImpl();
LogicalExpression thenExpression = new FunctionCall(call.getName(), newArgs, call.getPosition()).accept(this, functionLookupContext);
if (errorCollector.hasErrors()) {
thenExpression = getExceptionFunction(errorCollector.toErrorString());
}
errorCollector = errorCollectors.pop();
IfExpression.IfCondition condition = new IfCondition(ifCondition, thenExpression);
ifConditions.add(condition);
}
LogicalExpression ifExpression = ifConditions.poll().expression;
while (!ifConditions.isEmpty()) {
ifExpression = IfExpression.newBuilder().setIfCondition(ifConditions.poll()).setElse(ifExpression).build();
}
args[i] = ifExpression;
return ifExpression.accept(this, functionLookupContext);
}
throw new UnsupportedOperationException("Did not find any Union input types");
}
/**
* Simple version (testing one by one), which is very slow. Only for testing purposes.
*
* @param position
* @param mask
* @param data
* @param width
* @param height
* @param value
*/
public static void simple_fill(Vector2D position, byte[] mask, int[] data, int width, int height, int value) {
// create queue and add initial position
Queue<Vector2D> queue = new ArrayDeque<>();
queue.add(position);
// unit vectors in x and y direction
final Vector2D ex = new Vector2D(1, 0);
final Vector2D ey = new Vector2D(0, 1);
// the heap loop
while (!queue.isEmpty()) {
// get next point
Vector2D p = queue.remove();
int i = p.x + p.y * width;
if (mask[i] != 0) {
// mark as processed and set data to value
mask[i] = 0;
data[i] = value;
// up
if (p.y > 0) {
queue.add(Vector2D.subtract(p, ey));
}
// down
if (p.y < height - 1) {
queue.add(Vector2D.add(p, ey));
}
// left
if (p.x > 0) {
queue.add(Vector2D.subtract(p, ex));
}
// right
if (p.x < width - 1) {
queue.add(Vector2D.add(p, ex));
}
}
}
}