public static void main(String[] args) { LinkedList books = new LinkedList(); // 将字符串元素加入队列的尾部 books.offer("疯狂Java讲义"); // 将一个字符串元素加入栈的顶部 books.push("轻量级Java EE企业应用实战"); // 将字符串元素添加到队列的头部(相当于栈的顶部) books.offerFirst("疯狂Android讲义"); // 以List的方式(按索引访问的方式)来遍历集合元素 for (int i = 0; i < books.size(); i++) { System.out.println("遍历中:" + books.get(i)); } // 访问、并不删除栈顶的元素 System.out.println(books.peekFirst()); // 访问、并不删除队列的最后一个元素 System.out.println(books.peekLast()); // 将栈顶的元素弹出“栈” System.out.println(books.pop()); // 下面输出将看到队列中第一个元素被删除 System.out.println(books); // 访问、并删除队列的最后一个元素 System.out.println(books.pollLast()); // 下面输出:[轻量级Java EE企业应用实战] System.out.println(books); }
void startIdleState() { lock.lock(); try { final Thread currentThread = Thread.currentThread(); final Thread currentIdleThread = threadsRequestingIdle.peekFirst(); if (currentIdleThread == currentThread) { assert idleStateCount > 0; ++idleStateCount; assert idleStateCount > 0; return; } threadsRequestingIdle.add(currentThread); while ((activitiyCount > 0) || (threadsRequestingIdle.getFirst() != currentThread)) condition.awaitUninterruptibly(); assert idleStateCount == 0; assert activitiyCount == 0; assert threadsRequestingIdle.getFirst() == currentThread; idleStateCount = 1; } finally { lock.unlock(); } }
/** * Replaces the entire stack with this fragment. * * @param args Arguments to be set on the fragment using {@link * Fragment#setArguments(android.os.Bundle)}. */ public void replace(Class<?> fragment, String tag, Bundle args) { Fragment first = stack.peekFirst(); if (first != null && tag.equals(first.getTag())) { if (stack.size() > 1) { ensureTransaction(); fragmentTransaction.setCustomAnimations(popStackEnterAnimation, popStackExitAnimation); while (stack.size() > 1) { removeFragment(stack.pollLast()); } attachFragment(stack.peek(), tag); } return; } Fragment f = fragmentManager.findFragmentByTag(tag); if (f == null) { f = Fragment.instantiate(activity, fragment.getName(), args); } ensureTransaction(); fragmentTransaction.setCustomAnimations(enterAnimation, exitAnimation); clear(); attachFragment(f, tag); stack.add(f); topLevelTags.add(tag); }
public T pop() { if (!buf.isEmpty()) { T ret = buf.peekFirst(); buf.clear(); isBacktracking = true; return ret; } throw new IllegalStateException("Can't pop an empty ringbuffer"); }
public Vertex(LinkedList<Character> entrada, ArrayList<Vertex> destiny) { consecutivo = destiny.size(); destiny.add(this); value = entrada.pollFirst(); if (entrada.isEmpty() || entrada.peekFirst() != '(') { sons = new DLL(); } else { entrada.pollFirst(); Vertex actual = new Vertex(entrada, destiny); actual.sons.add(this); sons = new DLL(actual); while (entrada.peekFirst() == ',') { entrada.pollFirst(); actual = new Vertex(entrada, destiny); actual.sons.add(this); sons.add(actual); } entrada.pollFirst(); } }
public static void main(String a[]) { LinkedList<String> arrl = new LinkedList<String>(); arrl.add("First"); arrl.add("Second"); arrl.add("Third"); arrl.add("Random"); System.out.println("First Element: " + arrl.element()); System.out.println("First Element: " + arrl.getFirst()); System.out.println("First Element: " + arrl.peek()); System.out.println("First Element: " + arrl.peekFirst()); }
public void clear() { Fragment first = stack.peekFirst(); for (Fragment f : stack) { if (f == first) { detachFragment(f); } else { removeFragment(f); } } stack.clear(); }
void endAllowingFileScopeRequests() { lock.lock(); try { final Thread currentThread = Thread.currentThread(); final Thread currentIdleThread = threadsRequestingIdle.peekFirst(); assert currentThread == currentIdleThread; assert allowFileScopeRequests; while (activitiyCount > 0) condition.awaitUninterruptibly(); allowFileScopeRequests = false; } finally { lock.unlock(); } }
void startAllowingFileScopeRequests() { lock.lock(); try { final Thread currentThread = Thread.currentThread(); final Thread currentIdleThread = threadsRequestingIdle.peekFirst(); assert currentThread == currentIdleThread; assert !allowFileScopeRequests; allowFileScopeRequests = true; condition.signalAll(); } finally { lock.unlock(); } }
/** * add * * @param historyList * @param maxHistoryLength max. length of history or HISTORY_LENGTH_INFINTE * @param direction history direction order * @param addEntry */ private static void add( LinkedList<String> historyList, int maxHistoryLength, Directions direction, String addEntry) { switch (direction) { case ASCENDING: { String lastEntry = historyList.peekLast(); if ((lastEntry == null) || !lastEntry.equals(addEntry)) { historyList.add(addEntry); while (historyList.size() > maxHistoryLength) { historyList.removeFirst(); } } } break; case DESCENDING: { String firstEntry = historyList.peekFirst(); if ((firstEntry == null) || !firstEntry.equals(addEntry)) { historyList.addFirst(firstEntry); while (historyList.size() > maxHistoryLength) { historyList.removeLast(); } } } break; case SORTED: { boolean existsFlag = false; for (String entry : historyList) { if (entry.equals(addEntry)) { existsFlag = true; break; } } if (!existsFlag) { historyList.addFirst(addEntry); Collections.sort( historyList, new Comparator<String>() { public int compare(String data0, String data1) { return data0.compareTo(data1); } }); while (historyList.size() > maxHistoryLength) { historyList.removeLast(); } } } break; } }
private static Map<IProjectStage, List<IProjectStageSkill>> extractStageToSkillMap( List<IProjectStage> stages, List<IProjectStageSkill> skillsList) { Map<IProjectStage, List<IProjectStageSkill>> stageToSkillListMap = Maps.newHashMap(); LinkedList<IProjectStageSkill> skillListCopy = Lists.newLinkedList(skillsList); for (IProjectStage stage : stages) { Set<IProjectStageSkill> skillSet = stage.getProjectStageSkills(); List<IProjectStageSkill> entryList = Lists.newLinkedList(); while (skillSet.contains(skillListCopy.peekFirst())) { entryList.add(skillListCopy.pollFirst()); } stageToSkillListMap.put(stage, entryList); } return stageToSkillListMap; }
/** 测试LinkedList以双向链表的使用方法 */ private static void testLinkedListDeque() { System.out.println( "Test methods: addFirst(object), addLast(object), offerFirst(), offerLast(), getFirst(object), getLast(object), pollFirst(), pollLast(), peekFirst(), peekLast(), removeFirst(), removeLast()"); // 将 “abcdefg”初始化到LinkedList中 LinkedList<String> list = new LinkedList<String>(); // addFirst/addLast 没有返回值、offerFirst/offerLast返回true、内部都是调用Entry.addBefore()来添加的 list.addFirst("c"); list.offerFirst("b"); list.offerFirst("a"); list.addLast("d"); list.addLast("e"); list.offerLast("f"); printList(list); /* 相同: * getFirst/getLast、peekFirst/peekLast方法都是获取第一个元素、 * 不同: * getXXX方法在list的size为0抛出异常、 * peekXX方法在list的size为0返回null、 */ printStr("list getFirst() obtains element: " + list.getFirst()); printStr("list peekFirst() obtains element: " + list.peekFirst()); printStr("list getLast() obtains element: " + list.getLast()); printStr("list peekLast() obtains element: " + list.peekLast()); printList(list); /* * 相同: * pollXXX、removeXXX都是获取第一个元素、并且将此元素从list中移除 * 不同: * removeXXX方法在list的size为0抛出异常、 * pollXXX方法在list的size为0返回null、 */ printStr(list.pollFirst()); printStr(list.removeFirst()); printList(list); printStr(list.pollLast()); printStr(list.removeLast()); printList(list); }
/** Removes all added fragments and clears the stack. */ public void destroy() { ensureTransaction(); fragmentTransaction.setCustomAnimations(enterAnimation, exitAnimation); final Fragment topFragment = stack.peekFirst(); for (Fragment f : stack) { if (f != topFragment) { removeFragment(f); } } stack.clear(); for (String tag : topLevelTags) { removeFragment(fragmentManager.findFragmentByTag(tag)); } fragmentTransaction.commitAllowingStateLoss(); fragmentTransaction = null; }
void endIdleState() { lock.lock(); try { final Thread currentThread = Thread.currentThread(); assert currentThread == threadsRequestingIdle.getFirst(); assert !allowFileScopeRequests; assert idleStateCount > 0; assert activitiyCount == 0; --idleStateCount; assert idleStateCount >= 0; if (idleStateCount == 0) { threadsRequestingIdle.remove(); assert currentThread != threadsRequestingIdle.peekFirst(); condition.signalAll(); } } finally { lock.unlock(); } }
/** * Updates the snake's position and size. * * @return Tile tile that the head moved into. */ private TileType updateSnake() { /* * Here we peek at the next direction rather than polling it. While * not game breaking, polling the direction here causes a small bug * where the snake's direction will change after a game over (though * it will not move). */ Direction direction = directions.peekFirst(); /* * Here we calculate the new point that the snake's head will be at * after the update. */ Point head = new Point(snake.peekFirst()); switch (direction) { case North: head.y--; break; case South: head.y++; break; case West: head.x--; break; case East: head.x++; break; } /* * If the snake has moved out of bounds ('hit' a wall), we can just * return that it's collided with itself, as both cases are handled * identically. */ if (head.x < 0 || head.x >= BoardPanel.COL_COUNT || head.y < 0 || head.y >= BoardPanel.ROW_COUNT) { return TileType.SnakeBody; // Pretend we collided with our body. } /* * Here we get the tile that was located at the new head position and * remove the tail from of the snake and the board if the snake is * long enough, and the tile it moved onto is not a fruit. * * If the tail was removed, we need to retrieve the old tile again * incase the tile we hit was the tail piece that was just removed * to prevent a false game over. */ TileType old = board.getTile(head.x, head.y); if (old != TileType.Fruit && snake.size() > MIN_SNAKE_LENGTH) { Point tail = snake.removeLast(); board.setTile(tail, null); old = board.getTile(head.x, head.y); } /* * Update the snake's position on the board if we didn't collide with * our tail: * * 1. Set the old head position to a body tile. * 2. Add the new head to the snake. * 3. Set the new head position to a head tile. * * If more than one direction is in the queue, poll it to read new * input. */ if (old != TileType.SnakeBody) { board.setTile(snake.peekFirst(), TileType.SnakeBody); snake.push(head); board.setTile(head, TileType.SnakeHead); if (directions.size() > 1) { directions.poll(); } } return old; }
/** * Finally, synchronize our history with the Leader. * * @param newLeaderZxid * @throws IOException * @throws InterruptedException */ protected void syncWithLeader(long newLeaderZxid) throws IOException, InterruptedException { QuorumPacket ack = new QuorumPacket(Leader.ACK, 0, null); QuorumPacket qp = new QuorumPacket(); long newEpoch = ZxidUtils.getEpochFromZxid(newLeaderZxid); readPacket(qp); LinkedList<Long> packetsCommitted = new LinkedList<Long>(); LinkedList<PacketInFlight> packetsNotCommitted = new LinkedList<PacketInFlight>(); synchronized (zk) { if (qp.getType() == Leader.DIFF) { LOG.info("Getting a diff from the leader 0x" + Long.toHexString(qp.getZxid())); } else if (qp.getType() == Leader.SNAP) { LOG.info("Getting a snapshot from leader"); // The leader is going to dump the database // clear our own database and read zk.getZKDatabase().clear(); zk.getZKDatabase().deserializeSnapshot(leaderIs); String signature = leaderIs.readString("signature"); if (!signature.equals("BenWasHere")) { LOG.error("Missing signature. Got " + signature); throw new IOException("Missing signature"); } zk.getZKDatabase().commit(); zk.getZKDatabase().getM2mData().clear(); } else if (qp.getType() == Leader.TRUNC) { // we need to truncate the log to the lastzxid of the leader LOG.warn( "Truncating log to get in sync with the leader 0x" + Long.toHexString(qp.getZxid())); boolean truncated = zk.getZKDatabase().truncateLog(qp.getZxid()); if (!truncated) { // not able to truncate the log LOG.error("Not able to truncate the log " + Long.toHexString(qp.getZxid())); System.exit(13); } } else { LOG.error("Got unexpected packet from leader " + qp.getType() + " exiting ... "); System.exit(13); } zk.getZKDatabase().setlastProcessedZxid(qp.getZxid()); zk.createSessionTracker(); long lastQueued = 0; // in V1.0 we take a snapshot when we get the NEWLEADER message, but // in pre V1.0 // we take the snapshot at the UPDATE, since V1.0 also gets the // UPDATE (after the NEWLEADER) // we need to make sure that we don't take the snapshot twice. boolean snapshotTaken = false; // we are now going to start getting transactions to apply followed // by an UPTODATE outerLoop: while (self.isRunning()) { readPacket(qp); switch (qp.getType()) { case Leader.PROPOSAL: PacketInFlight pif = new PacketInFlight(); pif.hdr = new M2mTxnHeader(); pif.rec = M2mSerializeUtils.deserializeTxn(qp.getData(), pif.hdr); if (pif.hdr.getZxid() != lastQueued + 1) { LOG.warn( "Got zxid 0x" + Long.toHexString(pif.hdr.getZxid()) + " expected 0x" + Long.toHexString(lastQueued + 1)); } lastQueued = pif.hdr.getZxid(); packetsNotCommitted.add(pif); break; case Leader.COMMIT: if (!snapshotTaken) { pif = packetsNotCommitted.peekFirst(); if (pif.hdr.getZxid() != qp.getZxid()) { LOG.warn( "Committing " + qp.getZxid() + ", but next proposal is " + pif.hdr.getZxid()); } else { zk.processTxn(pif.hdr, pif.rec); packetsNotCommitted.remove(); } } else { packetsCommitted.add(qp.getZxid()); } break; case Leader.INFORM: /* * Only observer get this type of packet. We treat this as * receiving PROPOSAL and COMMMIT. */ PacketInFlight packet = new PacketInFlight(); packet.hdr = new M2mTxnHeader(); packet.rec = M2mSerializeUtils.deserializeTxn(qp.getData(), packet.hdr); // Log warning message if txn comes out-of-order if (packet.hdr.getZxid() != lastQueued + 1) { LOG.warn( "Got zxid 0x" + Long.toHexString(packet.hdr.getZxid()) + " expected 0x" + Long.toHexString(lastQueued + 1)); } lastQueued = packet.hdr.getZxid(); if (!snapshotTaken) { // Apply to db directly if we haven't taken the snapshot zk.processTxn(packet.hdr, packet.rec); } else { packetsNotCommitted.add(packet); packetsCommitted.add(qp.getZxid()); } break; case Leader.UPTODATE: if (!snapshotTaken) { // true for the pre v1.0 case zk.takeSnapshot(); self.setCurrentEpoch(newEpoch); } self.cnxnFactory.addZooKeeperServer(self.getHandleIp(), zk); break outerLoop; case Leader.NEWLEADER: // it will be NEWLEADER in v1.0 // Create updatingEpoch file and remove it after current // epoch is set. QuorumPeer.loadDataBase() uses this file to // detect the case where the server was terminated after // taking a snapshot but before setting the current epoch. // File updating = new // File(self.getTxnFactory().getSnapDir(), // QuorumPeer.UPDATING_EPOCH_FILENAME); // if (!updating.exists() && !updating.createNewFile()) { // throw new IOException("Failed to create " // + updating.toString()); // } // zk.takeSnapshot(); // self.setCurrentEpoch(newEpoch); // if (!updating.delete()) { // throw new IOException("Failed to delete " // + updating.toString()); // } snapshotTaken = true; writePacket(new QuorumPacket(Leader.ACK, newLeaderZxid, null), true); break; } } } ack.setZxid(ZxidUtils.makeZxid(newEpoch, 0)); writePacket(ack, true); sock.setSoTimeout(self.tickTime * self.syncLimit); zk.startup(); /* * Update the election vote here to ensure that all members of the * ensemble report the same vote to new servers that start up and send * leader election notifications to the ensemble. * * @see https://issues.apache.org/jira/browse/ZOOKEEPER-1732 */ self.updateElectionVote(newEpoch); // We need to log the stuff that came in between the snapshot and the // uptodate if (zk instanceof FollowerZooKeeperServer) { FollowerZooKeeperServer fzk = (FollowerZooKeeperServer) zk; for (PacketInFlight p : packetsNotCommitted) { fzk.logRequest(p.hdr, p.rec); } for (Long zxid : packetsCommitted) { fzk.commit(zxid); } } else { // New server type need to handle in-flight packets throw new UnsupportedOperationException("Unknown server type"); } }
@Override public Solution getBest() { return solutions.peekFirst(); }
public MockCatalogBuilder commit() { if (!featureTypes.isEmpty() || !coverages.isEmpty()) { if (!featureTypes.isEmpty()) { DataStoreInfo ds = dataStores.peekLast(); expect(catalog.getResourcesByStore(ds, FeatureTypeInfo.class)) .andReturn(featureTypes) .anyTimes(); expect(catalog.getResourcesByStore(ds, ResourceInfo.class)) .andReturn((List) featureTypes) .anyTimes(); expect(catalog.getFeatureTypesByDataStore(ds)).andReturn(featureTypes).anyTimes(); } if (!coverages.isEmpty()) { CoverageStoreInfo cs = coverageStores.peekLast(); expect(catalog.getResourcesByStore(cs, CoverageInfo.class)).andReturn(coverages).anyTimes(); expect(catalog.getResourcesByStore(cs, ResourceInfo.class)) .andReturn((List) coverages) .anyTimes(); expect(catalog.getCoveragesByCoverageStore(cs)).andReturn(coverages).anyTimes(); } // clear out local lists but push up to be included when this workspace is complete featureTypesByNamespace.addAll(featureTypes); featureTypes = new LinkedList<FeatureTypeInfo>(); coveragesByNamespace.addAll(coverages); coverages = new LinkedList<CoverageInfo>(); } else if (!dataStores.isEmpty() || !coverageStores.isEmpty()) { WorkspaceInfo ws = workspaces.peekLast(); NamespaceInfo ns = namespaces.peekLast(); expect(catalog.getStoresByWorkspace(ws.getName(), DataStoreInfo.class)) .andReturn(dataStores) .anyTimes(); expect(catalog.getStoresByWorkspace(ws, DataStoreInfo.class)) .andReturn(dataStores) .anyTimes(); expect(catalog.getDataStoresByWorkspace(ws.getName())).andReturn(dataStores).anyTimes(); expect(catalog.getDataStoresByWorkspace(ws)).andReturn(dataStores).anyTimes(); expect(catalog.getStoresByWorkspace(ws.getName(), CoverageStoreInfo.class)) .andReturn(coverageStores) .anyTimes(); expect(catalog.getStoresByWorkspace(ws, CoverageStoreInfo.class)) .andReturn(coverageStores) .anyTimes(); expect(catalog.getCoverageStoresByWorkspace(ws.getName())) .andReturn(coverageStores) .anyTimes(); expect(catalog.getCoverageStoresByWorkspace(ws)).andReturn(coverageStores).anyTimes(); List<StoreInfo> l = new LinkedList<StoreInfo>(dataStores); l.addAll(coverageStores); expect(catalog.getStoresByWorkspace(ws.getName(), StoreInfo.class)).andReturn(l).anyTimes(); expect(catalog.getStoresByWorkspace(ws, StoreInfo.class)).andReturn(l).anyTimes(); // add all the resources for this workspace List<ResourceInfo> m = new LinkedList(featureTypesByNamespace); m.addAll(coveragesByNamespace); expect(catalog.getResourcesByNamespace(ns, ResourceInfo.class)).andReturn(m).anyTimes(); // expect(catalog.getResourcesByNamespace(ns.getPrefix(), // ResourceInfo.class)).andReturn(m).anyTimes(); expect(catalog.getResourcesByNamespace(ns, FeatureTypeInfo.class)) .andReturn(featureTypesByNamespace) .anyTimes(); // expect(catalog.getResourcesByNamespace(ns.getPrefix(), FeatureTypeInfo.class)) // .andReturn(featureTypesByNamespace).anyTimes(); expect(catalog.getResourcesByNamespace(ns, CoverageInfo.class)) .andReturn(coveragesByNamespace) .anyTimes(); // expect(catalog.getResourcesByNamespace(ns.getPrefix(), CoverageInfo.class)) // .andReturn(coveragesByNamespace).anyTimes(); dataStoresAll.addAll(dataStores); dataStores = new LinkedList(); coverageStoresAll.addAll(coverageStores); coverageStores = new LinkedList(); featureTypesAll.addAll(featureTypesByNamespace); featureTypesByNamespace = new LinkedList(); coveragesAll.addAll(coveragesByNamespace); coveragesByNamespace = new LinkedList(); } else if (!workspaces.isEmpty()) { // all the resources List<ResourceInfo> l = new LinkedList<ResourceInfo>(featureTypesAll); l.addAll(coveragesAll); expect(catalog.getResources(ResourceInfo.class)).andReturn(l).anyTimes(); expect(catalog.getResources(FeatureTypeInfo.class)).andReturn(featureTypesAll).anyTimes(); expect(catalog.getResources(CoverageInfo.class)).andReturn(coverages).anyTimes(); expect(catalog.getFeatureTypes()).andReturn(featureTypesAll).anyTimes(); expect(catalog.getCoverages()).andReturn(coveragesAll).anyTimes(); // add all the stores List<StoreInfo> m = new LinkedList<StoreInfo>(dataStoresAll); m.addAll(coverageStoresAll); expect(catalog.getStores(StoreInfo.class)).andReturn(m).anyTimes(); expect(catalog.getStores(DataStoreInfo.class)).andReturn(dataStoresAll).anyTimes(); expect(catalog.getStores(CoverageStoreInfo.class)).andReturn(coverageStoresAll).anyTimes(); // add all the styles expect(catalog.getStyles()).andReturn(styles).anyTimes(); // add all the layer groups expect(catalog.getLayerGroups()).andReturn(layerGroups).anyTimes(); // add all the workspaces/namespaces expect(catalog.getWorkspaces()).andReturn(workspaces).anyTimes(); expect(catalog.getNamespaces()).andReturn(namespaces).anyTimes(); // default workspace/namespace expect(catalog.getDefaultWorkspace()).andReturn(workspaces.peekFirst()).anyTimes(); expect(catalog.getDefaultNamespace()).andReturn(namespaces.peekFirst()).anyTimes(); replay(catalog); featureTypesAll = new LinkedList(); coveragesAll = new LinkedList(); dataStoresAll = new LinkedList(); coverageStoresAll = new LinkedList(); styles = new LinkedList(); workspaces = new LinkedList(); namespaces = new LinkedList(); } return this; }