Java 类java.util.ArrayDeque 实例源码

项目:Cubes_2    文件:SunLight.java   
private static void tryPropagateRemove(ArrayDeque<LightNode> removeQueue, ArrayDeque<LightNode> addQueue,
        LightWorldSection w, int x, int y, int z, int l) {
    int dX = CoordinateConverter.area(x) - w.initialAreaX;
    int dZ = CoordinateConverter.area(z) - w.initialAreaZ;
    Area a = w.areas[dX + 1][dZ + 1];
    int ref = getRef(x - a.minBlockX, y, z - a.minBlockZ);
    if (!a.isReady() || y > a.maxY || !TransparencyManager.isTransparent(a.blocks[ref]))
        return;
    int p = ((a.light[ref] >> 4) & 0xF);
    if (p != 0 && p < l) {
        a.light[ref] = (byte) (a.light[ref] & 0xF); // same as
                                                    // ((a.light[ref] &
                                                    // 0xF0) | (0 << 4))
        a.updateRender(y / SIZE_BLOCKS);
        a.modify();
        removeQueue.add(new LightNode(x, y, z, p));
    } else if (p >= l) {
        addQueue.add(new LightNode(x, y, z, p));
    }
}
项目:openjdk-jdk10    文件:ArrayDeque8Test.java   
/**
 * Spliterator characteristics are as advertised
 */
public void testSpliterator_characteristics() {
    ArrayDeque q = new ArrayDeque();
    Spliterator s = q.spliterator();
    int characteristics = s.characteristics();
    int required = Spliterator.NONNULL
        | Spliterator.ORDERED
        | Spliterator.SIZED
        | Spliterator.SUBSIZED;
    assertEquals(required, characteristics & required);
    assertTrue(s.hasCharacteristics(required));
    assertEquals(0, characteristics
                 & (Spliterator.CONCURRENT
                    | Spliterator.DISTINCT
                    | Spliterator.IMMUTABLE
                    | Spliterator.SORTED));
}
项目:Reer    文件:Types.java   
/**
 * Visits all types in a type hierarchy in breadth-first order, super-classes first and then implemented interfaces.
 *
 * @param clazz the type of whose type hierarchy to visit.
 * @param excludedTypes the types not to walk when encountered in the hierarchy.
 * @param visitor the visitor to call for each type in the hierarchy.
 */
public static <T> void walkTypeHierarchy(Class<T> clazz, Collection<Class<?>> excludedTypes, TypeVisitor<? extends T> visitor) {
    Set<Class<?>> seenInterfaces = Sets.newHashSet();
    Queue<Class<? super T>> queue = new ArrayDeque<Class<? super T>>();
    queue.add(clazz);
    Class<? super T> type;
    while ((type = queue.poll()) != null) {
        if (excludedTypes.contains(type)) {
            continue;
        }

        visitor.visitType(type);

        Class<? super T> superclass = type.getSuperclass();
        if (superclass != null) {
            queue.add(superclass);
        }
        for (Class<?> iface : type.getInterfaces()) {
            if (seenInterfaces.add(iface)) {
                queue.add(Cast.<Class<? super T>>uncheckedCast(iface));
            }
        }
    }
}
项目:HackerRank_solutions    文件:Solution.java   
private static void findDistances(Node start) {
    if (start == null) {
        return;
    }
    ArrayDeque<Node> deque = new ArrayDeque<>(); // use deque as a queue
    start.distance = 0;
    deque.add(start);
    while (!deque.isEmpty()) {
        Node curr = deque.remove();
        for (Node neighbor : curr.neighbors) {
            if (neighbor.distance == -1) { // meaning it's unvisited
                neighbor.distance = curr.distance + EDGE_WEIGHT;
                deque.add(neighbor);
            }
        }
    }
}
项目:ACE_HackerRank    文件:Solution.java   
private static void findDistances(Node start) {
    if (start == null) {
        return;
    }
    ArrayDeque<Node> deque = new ArrayDeque<>(); // use deque as a queue
    start.distance = 0;
    deque.add(start);
    while (!deque.isEmpty()) {
        Node curr = deque.remove();
        for (Node neighbor : curr.neighbors) {
            if (neighbor.distance == -1) { // meaning it's unvisited
                neighbor.distance = curr.distance + EDGE_WEIGHT;
                deque.add(neighbor);
            }
        }
    }
}
项目:RxJava3-preview    文件:QueueDrainHelperTest.java   
@Test
public void postCompleteCancelled() {
    final TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
    ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
    AtomicLong state = new AtomicLong();
    BooleanSupplier isCancelled = new BooleanSupplier() {
        @Override
        public boolean getAsBoolean() throws Exception {
            return ts.isCancelled();
        }
    };

    ts.onSubscribe(new BooleanSubscription());
    queue.offer(1);
    state.getAndIncrement();
    ts.cancel();

    QueueDrainHelper.postComplete(ts, queue, state, isCancelled);

    ts.assertEmpty();
}
项目:RxJava3-preview    文件:QueueDrainHelperTest.java   
@Test
public void postCompleteEmpty() {
    TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
    ArrayDeque<Integer> queue = new ArrayDeque<Integer>();
    AtomicLong state = new AtomicLong();
    BooleanSupplier isCancelled = new BooleanSupplier() {
        @Override
        public boolean getAsBoolean() throws Exception {
            return false;
        }
    };

    ts.onSubscribe(new BooleanSubscription());

    QueueDrainHelper.postComplete(ts, queue, state, isCancelled);

    ts.assertResult();
}
项目:Cubes_2    文件:BlockLight.java   
private static void propagateAdd(ArrayDeque<LightNode> lightQueue, LightWorldSection w) {
    if (lightQueue.isEmpty())
        return;

    while (!lightQueue.isEmpty()) {
        LightNode n = lightQueue.pop();
        int x = n.x;
        int y = n.y;
        int z = n.z;
        int l = n.l;

        if (l <= 1)
            continue;

        tryPropagateAdd(lightQueue, w, x - 1, y, z, l);
        tryPropagateAdd(lightQueue, w, x + 1, y, z, l);
        tryPropagateAdd(lightQueue, w, x, y, z - 1, l);
        tryPropagateAdd(lightQueue, w, x, y, z + 1, l);
        if (y > 0)
            tryPropagateAdd(lightQueue, w, x, y - 1, z, l);
        tryPropagateAdd(lightQueue, w, x, y + 1, z, l);
    }
}
项目:openjdk-jdk10    文件:ArrayDequeTest.java   
/**
 * remove(x) removes x and returns true if present
 */
public void testRemoveElement() {
    ArrayDeque q = populatedDeque(SIZE);
    for (int i = 1; i < SIZE; i += 2) {
        assertTrue(q.contains(i));
        assertTrue(q.remove(i));
        assertFalse(q.contains(i));
        assertTrue(q.contains(i - 1));
    }
    for (int i = 0; i < SIZE; i += 2) {
        assertTrue(q.contains(i));
        assertTrue(q.remove(i));
        assertFalse(q.contains(i));
        assertFalse(q.remove(i + 1));
        assertFalse(q.contains(i + 1));
    }
    assertTrue(q.isEmpty());
}
项目:plugin-bt-jira    文件:JiraExportPluginResourceTest.java   
@Test
public void toStyleProcessorOverThreshold() {
    final Deque<Object> contextData = new ArrayDeque<>();
    contextData.add(1); // Index
    final SlaData data = new SlaData();
    data.setDuration(13L); // Duration;
    contextData.add(data);
    final JiraSlaComputations slaComputations = new JiraSlaComputations();
    final SlaConfiguration slaConfiguration0 = new SlaConfiguration();
    slaConfiguration0.setThreshold(14);
    final SlaConfiguration slaConfiguration1 = new SlaConfiguration();
    slaConfiguration1.setThreshold(12);
    slaComputations.setSlaConfigurations(Arrays.asList(slaConfiguration0, slaConfiguration1));
    Assert.assertEquals("invalid", resource.toStyleProcessor(slaComputations, "normal", "invalid").getValue(contextData));

}
项目:ProjectAres    文件:Types.java   
/**
 * Traverse ancestors of the given type, in the same order as {@link #ancestors(Class, boolean)},
 * and return the first ancestor for which the given predicate returns true.
 */
public static @Nullable <U> Class<? extends U> findAncestor(Class<? extends U> type, Class<U> upperBound, java.util.function.Predicate<Class<?>> pred) {
    Deque<Class<? extends U>> queue = new ArrayDeque<>();
    queue.add(type);
    while(!queue.isEmpty()) {
        final Class<? extends U> t = queue.remove();
        if(pred.test(t)) return t;

        if(t.getSuperclass() != null && upperBound.isAssignableFrom(t.getSuperclass())) {
            queue.add((Class<? extends U>) t.getSuperclass());
        }

        for(Class<?> iface : t.getInterfaces()) {
            if(upperBound.isAssignableFrom(iface)) {
                queue.add((Class<? extends U>) iface);
            }
        }
    }
    return null;
}
项目:MaxSim    文件:NodeWorkList.java   
public NodeWorkList(Graph graph, boolean fill, int iterationLimitPerNode) {
    visited = graph.createNodeBitMap();
    inQueue = graph.createNodeBitMap();
    if (fill) {
        ArrayDeque<Node> deque = new ArrayDeque<>(graph.getNodeCount());
        for (Node node : graph.getNodes()) {
            deque.add(node);
        }
        worklist = deque;
    } else {
        worklist = new ArrayDeque<>();
    }
    if (iterationLimitPerNode > 0) {
        iterationLimit = iterationLimitPerNode * graph.getNodeCount();
    }
}
项目:progex    文件:JavaDDGBuilder.java   
public DefUseVisitor(int iter, JavaClass[] classInfos, 
        DataDependenceGraph ddg, Map<ParserRuleContext, Object> pdNodes) {
    Logger.log("FILE IS: " + currentFile);
    this.ddg = ddg;
    changed = false;
    iteration = iter;
    analysisVisit = false;
    this.pdNodes = pdNodes;
    this.classInfos = classInfos;
    defList = new LinkedHashSet<>();
    useList = new LinkedHashSet<>();
    selfFlowList = new LinkedHashSet<>();
    activeClasses = new ArrayDeque<>();
    methodDefInfo = null;
    methodParams = new JavaField[0];
    localVars = new ArrayList<>();
}
项目:Cubes_2    文件:SunLight.java   
public static void initialSunlight(Area area) {
    initalSunlight.lock(); // used to prevent all the World Generation
                            // threads grabbing different areas and
                            // deadlocking
    LightWorldSection worldSection = new LightWorldSection(area);
    initalSunlight.unlock();

    ArrayDeque<LightNode> lightQueue = new ArrayDeque<>();
    int max = 15;
    for (int x = 0; x < SIZE_BLOCKS; x++) {
        for (int z = 0; z < SIZE_BLOCKS; z++) {
            int hmRef = getHeightMapRef(x, z);
            int h = area.heightmap[hmRef] + 1;

            int ref = getRef(x, h, z);
            for (int y = 0; y <= (area.maxY - h); y++) {
                int r = ref + (y * MAX_Y_OFFSET);
                area.light[r] = (byte) ((area.light[r] & 0xF) | (max << 4));
            }

            lightQueue.add(new LightNode(x + area.minBlockX, h, z + area.minBlockZ, max));
        }
    }
    propagateAdd(lightQueue, worldSection);
    worldSection.unlock();
}
项目:MathMax    文件:Parser.java   
public SyntaxTree parse( final List<Token> tokens ) {
    checkNotNull( tokens, "Null tokens list." );
    final Queue<Token> outputQueue = new LinkedList<Token>();
    final Deque<Token> operationStack = new ArrayDeque<>();
    for ( final Token token : tokens ) {
        if ( token.getType().isLiteral() ) {
            outputQueue.offer( token );
            continue;
        }
        if ( token.getType().isOperation() ) {
            processOperationToken( outputQueue, operationStack, token );
            continue;
        }
        if ( token.getType().isGrouper() ) {
            processGrouperTypeToken( outputQueue, operationStack, token );
        }
    }
    validateParenthesesMatching( operationStack );
    pushRemainingOperatorToOutput( outputQueue, operationStack );
    return SyntaxTree.create( outputQueue );
}
项目:Cubes_2    文件:BlockLight.java   
public static void spreadLight(int x, int y, int z, Area area, LightWorldSection w) {
    if (y >= 0 && y <= area.maxY) {
        ArrayDeque<LightNode> lightQueue = new ArrayDeque<LightNode>(1000);

        lightIf1(x, y, z, w, lightQueue);

        lightIf2(x, y, z, w, lightQueue);

        if (y <= w.maxY(x, z + 1) && (w.transparent(x, y, z + 1) || w.isLightSource(x, y, z + 1)))
            lightQueue.add(new LightNode(x, y, z + 1, w.getLight(x, y, z + 1)));
        if (y <= w.maxY(x, z - 1) && (w.transparent(x, y, z - 1) || w.isLightSource(x, y, z - 1)))
            lightQueue.add(new LightNode(x, y, z - 1, w.getLight(x, y, z - 1)));

        propagateAdd(lightQueue, w);
    }
}
项目:scancode    文件:CornerAnalyzer.java   
/**
 * Performs a BFS from a given starting pixel in order to determine the
 * border of the image.
 *
 * @param x the x coordinate of the starting point.
 * @param y the y coordinate of the starting point.
 */
private void bfsHelper(int x, int y) {
  Deque<Point<Integer>> queue = new ArrayDeque<>();
  queue.push(new Point<>(x, y));

  while (!queue.isEmpty()) {
    Point<Integer> popped = queue.pollLast();
    borderPoints.add(popped);

    for (int i = -1; i <= 1; i++) {
      for (int j = -1; j <= 1; j++) {
        Point<Integer> next = new Point<>(popped.getX() + i, popped.getY() + j);

        if (picture.contains(next) &&
            borderColor.sameColor(picture.getPixel(next.getX(), next.getY()),
                BLACK_SENSITIVITY) && !visited[next.getX()][next.getY()]) {
            visited[next.getX()][next.getY()] = true;
            queue.addLast(next);
        }
      }
    }
  }
}
项目:advent-of-code-2017    文件:Day12.java   
private static List<Integer> createConnectedComponent(HashMap<Integer, List<Integer>> graph, int root) {

    Queue<Integer> q = new ArrayDeque<>(); // next nodes to visit
    List<Integer> visited = new ArrayList<>(); // connected component so far
    q.add(root); // init queue

    while (!q.isEmpty()) {
        Integer poll = q.poll(); // get next node
        if (!visited.contains(poll)) { // if it's not already visited
            visited.add(poll); // visit it
            q.addAll(graph.get(poll)); // and put its neighbourhood in the queue
        }
    }
    visited.forEach(v -> graph.remove(v)); // removes the connected component from the graph
    return visited;

}
项目:Java-9-Programming-Blueprints    文件:DateCalcExpressionParser.java   
public Queue<Token> parse(String text) {
    final Queue<Token> tokens = new ArrayDeque<>();

    if (text != null) {
        text = text.trim();
        if (!text.isEmpty()) {
            boolean matchFound = false;
            for (InfoWrapper iw : infos) {
                final Matcher matcher = iw.pattern.matcher(text);
                if (matcher.find()) {
                    matchFound = true;
                    String match = matcher.group().trim();
                    tokens.add(iw.info.getToken(match));
                    tokens.addAll(parse(text.substring(match.length())));
                    break;
                }
            }
            if (!matchFound) {
                throw new DateCalcException("Could not parse the expression: " + text);
            }
        }
    }

    return tokens;
}
项目:Cubes    文件:BlockLight.java   
public static void spreadLight(int x, int y, int z, Area area, LightWorldSection w) {
  if (y >= 0 && y <= area.maxY) {
    ArrayDeque<LightNode> lightQueue = new ArrayDeque<LightNode>(1000);

    if (y <= w.maxY(x + 1, z) && (w.transparent(x + 1, y, z) || w.isLightSource(x + 1, y, z)))
      lightQueue.add(new LightNode(x + 1, y, z, w.getLight(x + 1, y, z)));
    if (y <= w.maxY(x - 1, z) && (w.transparent(x - 1, y, z) || w.isLightSource(x - 1, y, z)))
      lightQueue.add(new LightNode(x - 1, y, z, w.getLight(x - 1, y, z)));

    if (y < w.maxY(x, z) && (w.transparent(x, y + 1, z) || w.isLightSource(x, y + 1, z)))
      lightQueue.add(new LightNode(x, y + 1, z, w.getLight(x, y + 1, z)));
    if (y > 0 && (w.transparent(x, y - 1, z) || w.isLightSource(x, y - 1, z)))
      lightQueue.add(new LightNode(x, y - 1, z, w.getLight(x, y - 1, z)));

    if (y <= w.maxY(x, z + 1) && (w.transparent(x, y, z + 1) || w.isLightSource(x, y, z + 1)))
      lightQueue.add(new LightNode(x, y, z + 1, w.getLight(x, y, z + 1)));
    if (y <= w.maxY(x, z - 1) && (w.transparent(x, y, z - 1) || w.isLightSource(x, y, z - 1)))
      lightQueue.add(new LightNode(x, y, z - 1, w.getLight(x, y, z - 1)));

    propagateAdd(lightQueue, w);
  }
}
项目:boqa    文件:DepthFirstSearch.java   
/**
 * Generic implementation of BFS; forward/reverse edges are chosen using <code>selector</code>.
 *
 * @param g {@link DirectedGraph} to use for iteration.
 * @param v Vertex to start from.
 * @param visitor {@link VertexVisitor} to use for visiting vertices.
 * @param selector {@link NeighborSelector} for selecting forward/reverse vertices.
 */
@Override
protected void startFromImpl(DirectedGraph<V, E> g, V v, VertexVisitor<V, E> visitor,
    NeighborSelector<V, E> selector) {
  final Set<V> seen = new HashSet<V>();
  final ArrayDeque<V> dequeue = new ArrayDeque<V>();
  dequeue.addLast(v);
  while (!dequeue.isEmpty()) {
    final V vertex = dequeue.pollLast();
    if (!seen.contains(vertex)) { // skip seen ones
      seen.add(vertex);
      if (!visitor.visit(g, vertex)) {
        break;
      }
      final Iterator<V> it = selector.nextFrom(g, vertex);
      while (it.hasNext()) {
        dequeue.add(it.next());
      }
    }
  }
}
项目:myfaces-trinidad    文件:ForEachTag.java   
IterationUtils(
  FacesContext facesContext,
  String       parentComponentScopedId,
  String       jspId)
{
  Map<String, Object> viewAttrs = facesContext.getViewRoot().getAttributes();
  _iterationStatusMap = getIterationStatusMap(viewAttrs, true);

  Map<String, Object> reqMap = facesContext.getExternalContext().getRequestMap();
  Deque<IterationState> queue = (Deque<IterationState>)reqMap.get(
    _CURRENT_ITERATION_STATE_QUEUE_KEY);
  if (queue == null)
  {
    queue = new ArrayDeque<IterationState>(5);
    reqMap.put(_CURRENT_ITERATION_STATE_QUEUE_KEY, queue);
  }
  _iterationStateQueue = queue;

  _usedIterationIds = getUsedIterationIds(reqMap, true);
  _jspId = jspId;
  _parentComponentScopedId = parentComponentScopedId;
}
项目:myfaces-trinidad    文件:ComponentContextManagerImpl.java   
public SuspendedContextChanges suspend(FacesContext facesContext)
{
  if (_stack == null)
  {
    _LOG.fine("Stack with no changes has been suspended");
    return new SuspendedContextChangesImpl(new ArrayDeque<ComponentContextChange>(0));
  }

  ArrayDeque<ComponentContextChange> q = new ArrayDeque<ComponentContextChange>(_stack.size());
  for (ComponentContextChange change : _stack)
  {
    change.suspend(facesContext);
    q.offer(change);
  }

  _stack = null;

  if (_LOG.isFine())
  {
    _LOG.fine("Component change stack has been suspended. Number of suspended changes: {0}",
      new Object[] { q.size() });
  }

  return new SuspendedContextChangesImpl(q);
}
项目:SoftUni    文件:p08_NestedFolders.java   
public static void main(String[] args) throws IOException {
    final String stringPath = "files/Files-and-Streams" ;
    File file = new File(stringPath);
    PrintWriter writer = new PrintWriter("files/output08.txt");

    ArrayDeque<File> queue = new ArrayDeque<>();

    queue.offer(file);
    int counter = 1;
    while (!queue.isEmpty()){
        File currentDir = queue.poll();

        File[] nestedFiles = currentDir.listFiles();
        for (File nestedFile : nestedFiles) {
            if(nestedFile.isDirectory()){
                queue.offer(nestedFile);
                counter++;
            }
        }
        System.out.println(currentDir.getName());
        writer.println(currentDir.getName());
    }
    System.out.println(counter + " folders");
    writer.println(counter + " folders");
    writer.close();
}
项目:s-store    文件:ExecutionEngine.java   
/**
 * Add a single dependency. Exists only for test cases.
 * @param depId
 * @param vt
 */
void addDependency(final int depId, final VoltTable vt) {
    ArrayDeque<VoltTable> deque = m_depsById.get(depId);
    if (deque == null) {
        deque = new ArrayDeque<VoltTable>();
        m_depsById.put(depId, deque);
    }
    deque.add(vt);
}
项目:CTalk    文件:Translator.java   
@Override
public String visitElseIfFlow(GrammarParser.ElseIfFlowContext ctx) {
    locals.add(new ArrayDeque<>());
    final String ret = ctx.s.stream()
            .map(this::visit)
            .collect(Collectors.joining("\n",
                                        "else if (" + visit(ctx.c) + ")\n{\n",
                                        "\n}//"));
    locals.removeLast();
    return ret;
}
项目:openjdk-jdk10    文件:ArrayDequeTest.java   
/**
 * peekFirst() returns next element, or null if empty
 */
public void testPeekFirst() {
    ArrayDeque q = populatedDeque(SIZE);
    for (int i = 0; i < SIZE; ++i) {
        assertEquals(i, q.peekFirst());
        assertEquals(i, q.pollFirst());
        assertTrue(q.peekFirst() == null ||
                   !q.peekFirst().equals(i));
    }
    assertNull(q.peekFirst());
}
项目:openjdk-jdk10    文件:ArrayDequeTest.java   
/**
 * offerLast(x) succeeds
 */
public void testOfferLast() {
    ArrayDeque q = new ArrayDeque();
    assertTrue(q.offerLast(zero));
    assertTrue(q.offerLast(one));
    assertSame(zero, q.peekFirst());
    assertSame(one, q.peekLast());
}
项目:openjdk-jdk10    文件:ScopedPostOrderNodeIterator.java   
protected Deque<FixedNode> getScopes(StructuredGraph graph) {
    Deque<FixedNode> result = new ArrayDeque<>();
    result.push(graph.start());
    for (LoopBeginNode loopBegin : graph.getNodes(LoopBeginNode.TYPE)) {
        result.push(loopBegin);
    }
    return result;
}
项目:Reactive4JavaFlow    文件:FolyamSkipLast.java   
@Override
public boolean tryOnNext(T item) {
    ArrayDeque<T> q = this.queue;
    boolean b = true;
    if (q.size() == n) {
        b = actual.tryOnNext(q.poll());
    }
    q.offer(item);
    return b;
}
项目:HackerRank_solutions    文件:Solution.java   
private static boolean isBalanced(String expression, HashMap<Character, Character> map) {
    if ((expression.length() % 2) != 0) {
        return false; // odd length Strings are not balanced
    }        
    ArrayDeque<Character> deque = new ArrayDeque<>(); // use deque as a stack
    for (int i = 0; i < expression.length(); i++) {
        Character ch = expression.charAt(i);
        if (map.containsKey(ch)) {
            deque.push(ch);
        } else if (deque.isEmpty() || ch != map.get(deque.pop())) {
            return false;
        }
    }
    return deque.isEmpty();
}
项目:AssistantBySDK    文件:NavigatorService.java   
private Deque<Integer> formatConjestionDistance(List<RoadConditionItem> conditionItems, int eIndex, double totalDistance) {
    Deque<Integer> dists = new ArrayDeque<Integer>();
    RoadConditionItem item;
    int t;
    double maxIndex = conditionItems.get(conditionItems.size() - 1).curItemEndIndex;
    for (RoadConditionItem conditionItem : conditionItems) {
        conditionItem.curItemEndIndex = (int) (conditionItem.curItemEndIndex / maxIndex * totalDistance);
    }
    for (int i = 0; i < eIndex; i++) {
        item = conditionItems.get(i);
        if (dists.size() == 0) {
            if (item.roadConditionType > RoadConditionItem.ROAD_CONDITION_TYPE_Straightway) {
                dists.offer(i == 0 ? item.curItemEndIndex : item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex);
            }
        } else {
            t = dists.size();
            if ((t & 1) == 1) {//奇数,拥堵长度
                if (item.roadConditionType > RoadConditionItem.ROAD_CONDITION_TYPE_Straightway) {
                    dists.offer(dists.pollLast() + (item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                } else {
                    dists.offer((item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                }
            } else {//偶数,顺畅长度
                if (item.roadConditionType > RoadConditionItem.ROAD_CONDITION_TYPE_Straightway) {
                    if (dists.getLast() <= 100) {
                        dists.pollLast();
                        dists.offer(dists.pollLast() + (item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                    } else {
                        dists.offer((item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                    }
                } else {
                    dists.offer(dists.pollLast() + (item.curItemEndIndex - conditionItems.get(i - 1).curItemEndIndex));
                }
            }
        }
    }
    return dists;
}
项目:CTalk    文件:Translator.java   
@Override
public String visitElseFlow(GrammarParser.ElseFlowContext ctx) {
    locals.add(new ArrayDeque<>());
    final String ret = ctx.s.stream()
            .map(this::visit)
            .collect(Collectors.joining("\n", "else\n{\n", "\n}//"));
    locals.removeLast();
    return ret;
}
项目:HackerRank_solutions    文件:Solution.java   
private static boolean isBalanced(String expression, HashMap<Character, Character> map) {
    if ((expression.length() % 2) != 0) {
        return false; // odd length Strings are not balanced
    }        
    ArrayDeque<Character> deque = new ArrayDeque<>(); // use deque as a stack
    for (int i = 0; i < expression.length(); i++) {
        Character ch = expression.charAt(i);
        if (map.containsKey(ch)) {
            deque.push(ch);
        } else if (deque.isEmpty() || ch != map.get(deque.pop())) {
            return false;
        }
    }
    return deque.isEmpty();
}
项目:amanda    文件:AbstractSelfReferenceRepository.java   
/**
 * <strong>使用广度优先搜索收集</strong>当前实体及其所有子孙实体到集合,叶子实体排在最前面<br/>
 * 这样才能保证先删除子孙节点,后删除父节点,避免违反外键约束
 * @param currentEntity 存放当前实体及其所有子孙实体的集合
 * @param treeEntities 所有实体的集合
 * @return 当前实体及其所有子孙实体的集合,叶子实体排在集合最前面
 */
@SuppressWarnings("unchecked")
@Transactional
private LinkedList<SelfReference<T>> bfsTraverse(SelfReference<T> currentEntity, LinkedList<SelfReference<T>> treeEntities) {

    // 无法获取子孙类目时,在事务中重新获取当前节点
    try {
        currentEntity.getChildren().size();
    } catch (LazyInitializationException e) {
        ID id = (ID) ((BaseEntity)currentEntity).getId();
        currentEntity = (SelfReference<T>) findOne(id);
    }

    // 队列,用于广度优先遍历。每一时刻,队列所包含的节点是那些本身已经被访问,而它的邻居(这里即子节点)还有未被访问的节点
    Queue<SelfReference<T>> queue = new ArrayDeque<>();
    treeEntities.addFirst(currentEntity); // 对当前遍历到的元素执行的操作:加在头部,后续用于删除节点(避免违反外键约束)
    queue.add(currentEntity); // 加在尾部

    while (queue.size() != 0) { // 直到队列为空
        SelfReference<T> parent = queue.remove(); // 移除在队列头部的节点

        if(parent.getChildren().size() != 0) {
            parent.getChildren().forEach(child -> {
                treeEntities.addFirst((SelfReference<T>) child); // 对当前遍历到的元素执行的操作:加在头部
                queue.add((SelfReference<T>) child); // 加在尾部
            });
        }
    }

    return treeEntities;
}
项目:Cubes_2    文件:SunLight.java   
private static void addSunlightIf2(LightWorldSection w, int y, int z, int x, ArrayDeque<LightNode> lightQueue){
    if (y > 0 && w.transparent(x, y - 1, z))
        lightQueue.add(new LightNode(x, y - 1, z, w.getSunlight(x, y - 1, z)));
    if (y <= w.maxY(x, z + 1) && w.transparent(x, y, z + 1))
        lightQueue.add(new LightNode(x, y, z + 1, w.getSunlight(x, y, z + 1)));
    if (y <= w.maxY(x, z - 1) && w.transparent(x, y, z - 1))
        lightQueue.add(new LightNode(x, y, z - 1, w.getSunlight(x, y, z - 1)));

}
项目:BUILD_file_generator    文件:StronglyConnectedComponents.java   
StronglyConnectedComponents(Graph<N> graph) {
  this.graph = checkNotNull(graph);
  this.unassignedNodeStack = new ArrayDeque<>();
  this.numberOfNodesDiscovered = 0;
  this.tarjanMetadataMap = new HashMap<>();
  this.connectedComponents = new ImmutableList.Builder<>();
}
项目:learnjava8    文件:TestArrayDeque.java   
public static void main(String[] args) {

    ArrayDeque<Integer> ad = new ArrayDeque<>();

    // add element of array
    ad.add(3);
    ad.add(4);        
    System.out.println("Add Element. content: " + ad.toString());

    // add element to its first (head) & last (tail) index
    ad.addFirst(1);
    ad.addLast(5);
    System.out.println("AddFirst & AddLast. content: "+ ad.toString());

    // offers are similar to adds
    ad.offer(6);
    ad.offer(7);
    ad.offerFirst(0);
    ad.offerLast(8);
    System.out.println("Offers. content: " + ad.toString());
    System.out.println("Current size: " + ad.size());

    // peekFirst, peek, getFirst data
    System.out.println("Peek First data is " + ad.peekFirst());
    System.out.println("Peek data is " + ad.peek());
    System.out.println("GetFirst is " + ad.getFirst());

    // peekLast, getLast data
    System.out.println("Peek Last data is " + ad.peekLast());
    System.out.println("GetLast is " + ad.getLast());

    // polls, get data & remove from queue
    System.out.println("PollFirst data is " + ad.pollFirst() + ", content: " + ad.toString() );
    System.out.println("Poll data is " + ad.poll()+ ", content: " + ad.toString());
    System.out.println("PollLast data is " + ad.pollLast() + ", content: " + ad.toString());                
}
项目:GitHub    文件:CalendarPagerAdapter.java   
CalendarPagerAdapter(MaterialCalendarView mcv) {
    this.mcv = mcv;
    this.today = CalendarDay.today();
    currentViews = new ArrayDeque<>();
    currentViews.iterator();
    setRangeDates(null, null);
}
项目:FactionsXL    文件:EngineDynmap.java   
public int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) {
    int cnt = 0;
    ArrayDeque<int[]> stack = new ArrayDeque<>();
    stack.push(new int[]{x, y});

    while (!stack.isEmpty()) {
        int[] nxt = stack.pop();
        x = nxt[0];
        y = nxt[1];
        if (source.getFlag(x, y)) { // Set in src
            source.setFlag(x, y, false); // Clear source
            destination.setFlag(x, y, true); // Set in destination
            cnt++;
            if (source.getFlag(x + 1, y)) {
                stack.push(new int[]{x + 1, y});
            }
            if (source.getFlag(x - 1, y)) {
                stack.push(new int[]{x - 1, y});
            }
            if (source.getFlag(x, y + 1)) {
                stack.push(new int[]{x, y + 1});
            }
            if (source.getFlag(x, y - 1)) {
                stack.push(new int[]{x, y - 1});
            }
        }
    }
    return cnt;
}