Java Code Examples for java.util.LinkedList#isEmpty()
The following examples show how to use
java.util.LinkedList#isEmpty() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DataDstPb.java From xresloader with MIT License | 6 votes |
static private void setup_extension(DataDstOneofDescriptor child_field, Descriptors.Descriptor container, Descriptors.OneofDescriptor fd) { LinkedList<DataVerifyImpl> gen = setup_verifier(container, fd); if (gen != null && !gen.isEmpty()) { for (DataVerifyImpl vfy : gen) { child_field.addVerifier(vfy); } } else { child_field.resetVerifier(); } if (fd.getOptions().hasExtension(Xresloader.oneofDescription)) { child_field.mutableExtension().description = fd.getOptions().getExtension(Xresloader.oneofDescription); } if (fd.getOptions().hasExtension(Xresloader.oneofSeparator)) { child_field.mutableExtension().plainSeparator = fd.getOptions().getExtension(Xresloader.oneofSeparator); } }
Example 2
Source File: XSDExporter.java From CQL with GNU Affero General Public License v3.0 | 6 votes |
/** * protected method to assist in building "pullbackpath" strings for the * pullback constraint annotations * * @param inEdges List of sketchedges * @param includeLast Include the last or not * @return path like string */ protected String xmlPBJoinPath(final List<SketchEdge> inEdges, final boolean includeLast) { final LinkedList<SketchEdge> edges = new LinkedList<>(inEdges); final StringBuilder joinClause = new StringBuilder(quoteId(edges.get(0).getSourceEntity().getName())); if (!includeLast && !edges.isEmpty()) { edges.removeLast(); } for (final SketchEdge e : edges) { final EntityNode target = e.getTargetEntity(); joinClause.append('(').append(e.getName()).append(")->").append(target.getName()); } return joinClause.toString(); }
Example 3
Source File: TransferServiceImpl.java From packagedrone with Eclipse Public License 1.0 | 6 votes |
public void addChild ( final LinkedList<String> path, final ZipEntry zipEntry ) { final String seg = path.pop (); Entry child = this.children.get ( seg ); if ( child == null ) { final List<String> ids = new ArrayList<> ( this.ids ); ids.add ( seg ); child = new Entry ( ids ); this.children.put ( seg, child ); } if ( path.isEmpty () ) { child.zipEntry = zipEntry; } else { child.addChild ( path, zipEntry ); } }
Example 4
Source File: KthNode.java From coding-interviews with MIT License | 6 votes |
public TreeNode findKthNode(TreeNode pRoot, int k) { if (pRoot == null || k <= 0) return null; LinkedList<TreeNode> stack = new LinkedList<>(); int count = 0; while (pRoot != null || !stack.isEmpty()) { while (pRoot != null) { stack.push(pRoot); pRoot = pRoot.left; } if (!stack.isEmpty()) { pRoot = stack.pop(); if (++count == k) return pRoot; pRoot = pRoot.right; } } return null; }
Example 5
Source File: GenericTreeModel.java From olat with Apache License 2.0 | 6 votes |
/** * Searches (by breadth-first search) the node in this model whose user object is equal to the given object. * * @param object * @return The node whose user object is equal to the given object or null */ public TreeNode findNodeByUserObject(Object object) { LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); // initialize the queue by the root node queue.add(getRootNode()); do { // dequeue and examine TreeNode node = queue.poll(); Object currentNodesObject = node.getUserObject(); if (object.equals(currentNodesObject)) { return node; } else { // enqueue successors for (int i = 0; i < node.getChildCount(); i++) { queue.add((TreeNode) node.getChildAt(i)); } } } while (!queue.isEmpty()); // the node couldn't be found return null; }
Example 6
Source File: FileUtils.java From winter with Apache License 2.0 | 6 votes |
/** * @param root * @return returns a list of all files (including those in sub-directories) */ public static List<File> listAllFiles(File root) { LinkedList<File> files = new LinkedList<>(); if(root.isDirectory()) { LinkedList<File> toList = new LinkedList<>(Arrays.asList(root.listFiles())); while(!toList.isEmpty()) { File f = toList.poll(); if(f.isDirectory()) { toList.addAll(Arrays.asList(f.listFiles())); } else { files.add(f); } } } else { files.add(root); } return files; }
Example 7
Source File: StatsItem.java From DDMQ with Apache License 2.0 | 6 votes |
private static StatsSnapshot computeStatsData(final LinkedList<CallSnapshot> csList) { StatsSnapshot statsSnapshot = new StatsSnapshot(); synchronized (csList) { double tps = 0; double avgpt = 0; long sum = 0; if (!csList.isEmpty()) { CallSnapshot first = csList.getFirst(); CallSnapshot last = csList.getLast(); sum = last.getValue() - first.getValue(); tps = (sum * 1000.0d) / (last.getTimestamp() - first.getTimestamp()); long timesDiff = last.getTimes() - first.getTimes(); if (timesDiff > 0) { avgpt = (sum * 1.0d) / timesDiff; } } statsSnapshot.setSum(sum); statsSnapshot.setTps(tps); statsSnapshot.setAvgpt(avgpt); } return statsSnapshot; }
Example 8
Source File: VPAutomaton.java From symbolicautomata with Apache License 2.0 | 6 votes |
private void dfsReachRel(int stateFrom, Map<Integer, Integer> stateToId, boolean[][] reachRel, Map<Integer, Collection<Integer>> wmRelList) { HashSet<Integer> reached = new HashSet<>(); LinkedList<Integer> toVisit = new LinkedList<>(); toVisit.add(stateFrom); int id = stateToId.get(stateFrom); while (!toVisit.isEmpty()) { int state = toVisit.removeFirst(); // Epsilon Transition for (Integer to : wmRelList.get(state)) { if (!reached.contains(to)) { reachRel[id][stateToId.get(to)] = true; wmRelList.get(stateFrom).add(to); toVisit.add(to); reached.add(to); } } } }
Example 9
Source File: Tree.java From TrakEM2 with GNU General Public License v3.0 | 5 votes |
/** Can copy a Treeline to an AreaTree and viceversa. * Copies the transform, the nodes (with tags and confidence), and the color. The transparency, locked stated and links are not copied. */ static public<A extends Tree<?>, B extends Node<?>> A copyAs(final Tree<?> src, final Class<A> tree_class, final Class<B> node_class) throws Exception { final String title = "copy of " + src.title + " #" + src.id; final A t = tree_class.getConstructor(Project.class, String.class).newInstance(src.project, title); t.at.setTransform(src.at); t.color = src.color; t.width = src.width; t.height = src.height; final Map<Node<?>,B> rel = new HashMap<Node<?>,B>(); final LinkedList<Node<?>> todo = new LinkedList<Node<?>>(); //t.root = new Treeline.RadiusNode(src.root.x, src.root.y, src.root.la); todo.add(src.root); while (!todo.isEmpty()) { final Node<?> a = todo.removeLast(); // Put all children nodes to the end of the todo list if (null != a.children) for (final Node<?> child : a.children) todo.add(child); // Copy the content of the 'a' node final B copy = node_class.getConstructor(Float.TYPE, Float.TYPE, Layer.class).newInstance(a.x, a.y, a.la); copy.copyProperties(a); // Store relationship between original and copy rel.put(a, copy); // Find parent if any if (null == a.parent) { // Set the copy as the root t.root = (Node)copy; // need to cast continue; } // .. and if found, add the copy to the copied parent: rel.get(a.parent).add((Node)copy, copy.confidence); // TODO no other way than to cast? } // create internals t.cacheSubtree((Collection)t.root.getSubtreeNodes()); return t; }
Example 10
Source File: T64.java From cs-summary-reflection with Apache License 2.0 | 5 votes |
/** * 题目:滑动窗口的最大值 思路:滑动窗口应当是队列,但为了得到滑动窗口的最大值,队列序可以从两端删除元素,因此使用双端队列。 原则: 对新来的元素k,将其与双端队列中的元素相比较 * 1)前面比k小的,直接移出队列(因为不再可能成为后面滑动窗口的最大值了!), * 2)前面比k大的X,比较两者下标,判断X是否已不在窗口之内,不在了,直接移出队列,队列的第一个元素是滑动窗口中的最大值 */ public ArrayList<Integer> maxInWindows(int[] num, int size) { ArrayList<Integer> ret = new ArrayList<>(); if (num == null) { return ret; } if (num.length < size || size < 1) { return ret; } // 双端队列,用来记录每个窗口的最大值下标 LinkedList<Integer> indexDeque = new LinkedList<>(); for (int i = 0; i < size - 1; i++) { while (!indexDeque.isEmpty() && num[i] > num[indexDeque.getLast()]) { indexDeque.removeLast(); } indexDeque.addLast(i); } for (int i = size - 1; i < num.length; i++) { while (!indexDeque.isEmpty() && num[i] > num[indexDeque.getLast()]) { indexDeque.removeLast(); } indexDeque.addLast(i); if (i - indexDeque.getFirst() + 1 > size) { indexDeque.removeFirst(); } ret.add(num[indexDeque.getFirst()]); } return ret; }
Example 11
Source File: SocketIOWithTimeout.java From hadoop-gpu with Apache License 2.0 | 5 votes |
/** * Takes one selector from end of LRU list of free selectors. * If there are no selectors awailable, it creates a new selector. * Also invokes trimIdleSelectors(). * * @param channel * @return * @throws IOException */ private synchronized SelectorInfo get(SelectableChannel channel) throws IOException { SelectorInfo selInfo = null; SelectorProvider provider = channel.provider(); // pick the list : rarely there is more than one provider in use. ProviderInfo pList = providerList; while (pList != null && pList.provider != provider) { pList = pList.next; } if (pList == null) { //LOG.info("Creating new ProviderInfo : " + provider.toString()); pList = new ProviderInfo(); pList.provider = provider; pList.queue = new LinkedList<SelectorInfo>(); pList.next = providerList; providerList = pList; } LinkedList<SelectorInfo> queue = pList.queue; if (queue.isEmpty()) { Selector selector = provider.openSelector(); selInfo = new SelectorInfo(); selInfo.selector = selector; selInfo.queue = queue; } else { selInfo = queue.removeLast(); } trimIdleSelectors(System.currentTimeMillis()); return selInfo; }
Example 12
Source File: StatsItem.java From rocketmq-read with Apache License 2.0 | 5 votes |
/** * 计算数据 * @param csList csList * @return ; */ private static StatsSnapshot computeStatsData(final LinkedList<CallSnapshot> csList) { StatsSnapshot statsSnapshot = new StatsSnapshot(); synchronized (csList) { double tps = 0; double avgpt = 0; long sum = 0; if (!csList.isEmpty()) { CallSnapshot first = csList.getFirst(); CallSnapshot last = csList.getLast(); //sum=last-first sum = last.getValue() - first.getValue(); //tps tps = (sum * 1000.0d) / (last.getTimestamp() - first.getTimestamp()); long timesDiff = last.getTimes() - first.getTimes(); if (timesDiff > 0) { //平均rt avgpt = (sum * 1.0d) / timesDiff; } } statsSnapshot.setSum(sum); statsSnapshot.setTps(tps); statsSnapshot.setAvgpt(avgpt); } return statsSnapshot; }
Example 13
Source File: TomcatSecurityService.java From tomee with Apache License 2.0 | 5 votes |
@Override public Subject getRunAsSubject(final BeanContext callingBeanContext) { final Subject runAsSubject = super.getRunAsSubject(callingBeanContext); if (runAsSubject != null) { return runAsSubject; } final LinkedList<Subject> stack = RUN_AS_STACK.get(); if (stack.isEmpty()) { return null; } return stack.getFirst(); }
Example 14
Source File: ComponentNode.java From neoscada with Eclipse Public License 1.0 | 5 votes |
public void registerComponent ( final LinkedList<String> prefix, final ComponentFolder componentFolder, final Component component ) { logger.debug ( "Register - prefix: {}, componentFolder: {}, component: {}", prefix, componentFolder, component ); // first get the name final String next = prefix.pop (); if ( prefix.isEmpty () ) { add ( next, componentFolder, component ); } else { // add another sub level ComponentNode node = this.nodes.get ( next ); if ( node == null ) { if ( this.components.containsKey ( next ) ) { // blocked by component // remove all folders we might have created checkRemove (); // throw exception throw new IllegalStateException ( "Namespace blocked by other component" ); } final FolderCommon folder = new FolderCommon (); this.folder.add ( next, folder, null ); node = new ComponentNode ( this, folder ); this.nodes.put ( next, node ); } node.registerComponent ( prefix, componentFolder, component ); } }
Example 15
Source File: Recycler.java From CrossMobile with GNU Lesser General Public License v3.0 | 5 votes |
public synchronized V get(C category) { LinkedList<V> cat = storage.get(category); if (cat == null || cat.isEmpty()) return constructor == null ? null : constructor.invoke(category); V found = cat.removeLast(); if (found != null) resurrect.invoke(found); return found; }
Example 16
Source File: HostInfo.java From SPADE with GNU General Public License v3.0 | 4 votes |
/** * Returns all the 'configured' network interfaces * * @return list of network interfaces / NULL (in case of error) */ private static List<Interface> readInterfaces(){ try{ List<Interface> interfacesResult = new ArrayList<Interface>(); Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); LinkedList<NetworkInterface> networkInterfacesList = new LinkedList<NetworkInterface>(); while(networkInterfaces.hasMoreElements()){ networkInterfacesList.addLast(networkInterfaces.nextElement()); } while(!networkInterfacesList.isEmpty()){ NetworkInterface networkInterface = networkInterfacesList.removeFirst(); // Since there can be subinterfaces, adding all to the networkInterfaces list and processing them. // Breadth first traversal. Enumeration<NetworkInterface> networkSubInterfaces = networkInterface.getSubInterfaces(); while(networkSubInterfaces.hasMoreElements()){ networkInterfacesList.addLast(networkSubInterfaces.nextElement()); } Interface interfaceResult = new Interface(); interfaceResult.name = unNullify(networkInterface.getName()); interfaceResult.macAddress = parseBytesToMacAddress(networkInterface.getHardwareAddress()); List<String> ips = new ArrayList<String>(); Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); while(inetAddresses.hasMoreElements()){ InetAddress inetAddress = inetAddresses.nextElement(); byte[] ipBytes = inetAddress.getAddress(); if(inetAddress instanceof Inet4Address){ ips.add(parseBytesToIpv4(ipBytes)); }else if(inetAddress instanceof Inet6Address){ ips.add(parseBytesToIpv6(ipBytes)); }else{ logger.log(Level.WARNING, "Unknown address type: " + inetAddress); } } interfaceResult.ips = ips; interfacesResult.add(interfaceResult); } return interfacesResult; }catch(Exception e){ logger.log(Level.SEVERE, "Failed to poll network interfaces", e); } return null; }
Example 17
Source File: Nodes.java From netbeans with Apache License 2.0 | 4 votes |
private static Set<URL> findReverseSourceRoots(final URL thisSourceRoot, Map<URL, List<URL>> sourceDeps, Map<URL, List<URL>> rootPeers, final FileObject thisFile) { long startTime = System.currentTimeMillis(); try { //TODO: from SourceUtils (which filters out source roots that do not belong to open projects): //Create inverse dependencies final Map<URL, List<URL>> inverseDeps = new HashMap<URL, List<URL>> (); for (Map.Entry<URL,List<URL>> entry : sourceDeps.entrySet()) { final URL u1 = entry.getKey(); final List<URL> l1 = entry.getValue(); for (URL u2 : l1) { List<URL> l2 = inverseDeps.get(u2); if (l2 == null) { l2 = new ArrayList<URL>(); inverseDeps.put (u2,l2); } l2.add (u1); } } //Collect dependencies final Set<URL> result = new HashSet<URL>(); final LinkedList<URL> todo = new LinkedList<URL> (); todo.add (thisSourceRoot); List<URL> peers = rootPeers != null ? rootPeers.get(thisSourceRoot) : null; if (peers != null) todo.addAll(peers); while (!todo.isEmpty()) { final URL u = todo.removeFirst(); if (!result.contains(u)) { result.add (u); final List<URL> ideps = inverseDeps.get(u); if (ideps != null) { todo.addAll (ideps); } } } return result; } finally { long endTime = System.currentTimeMillis(); Logger.getLogger("TIMER").log(Level.FINE, "Find Reverse Source Roots", //NOI18N new Object[]{thisFile, endTime - startTime}); } }
Example 18
Source File: ConfigTemplateImpl.java From Diorite with MIT License | 4 votes |
@SuppressWarnings({"rawtypes", "unchecked"}) private void scanMethods(LinkedList<MethodInvoker> methods, Map<String, MethodInvoker> toKeyMappers, Map<String, MethodInvoker> toStringMappers, Set<String> knownProperties) { int sizeBefore = methods.size(); for (Iterator<MethodInvoker> iterator = methods.iterator(); iterator.hasNext(); ) { MethodInvoker methodInvoker = iterator.next(); ConfigPropertyTemplateImpl template; Class<?> returnType = methodInvoker.getReturnType(); Type genericReturnType = methodInvoker.getGenericReturnType(); String name; Method method = methodInvoker.getMethod(); if (methodInvoker.isPrivate()) { if (methodInvoker.isAnnotationPresent(ToKeyMapperFunction.class)) { this.scanKeyMapper(methodInvoker, toKeyMappers); iterator.remove(); continue; } if (methodInvoker.isAnnotationPresent(ToStringMapperFunction.class)) { this.scanStringMapper(methodInvoker, toStringMappers); iterator.remove(); continue; } name = this.extractName(methodInvoker); methodInvoker.ensureAccessible(); if (! knownProperties.add(name)) { throw new IllegalStateException("Duplicated property: " + name); } template = new ConfigPropertyTemplateImpl(this, returnType, genericReturnType, name, cfg -> methodInvoker.invoke(cfg), method); } else { Pair<ConfigPropertyAction, ActionMatcherResult> resultPair = ActionsRegistry.findMethod(method, knownProperties::contains); if (resultPair == null) { iterator.remove(); continue; } ConfigPropertyAction propertyAction = resultPair.getLeft(); if (! propertyAction.getActionName().equals("get") && methodInvoker.isDefault()) { throw new RuntimeException("Unexpected default implementation of: " + method); } ActionMatcherResult matcherResult = resultPair.getRight(); if (! matcherResult.isValidatedName()) { continue; // wait for validation. } name = matcherResult.getPropertyName(); ConfigPropertyTemplateImpl<?> oldTemplate = this.mutableProperties.get(name); if (oldTemplate != null) { template = oldTemplate; } else { if (! propertyAction.declaresProperty()) { continue; } if (! knownProperties.add(name)) { throw new IllegalStateException("Duplicated property: " + name); } template = new ConfigPropertyTemplateImpl(this, returnType, genericReturnType, name, cfg -> null, method); } if (propertyAction.getActionName().equals("get") && methodInvoker.isDefault()) { this.defaultValueFromDefaultMethod(methodInvoker, template); } MethodSignature methodSignature = new MethodSignature(method); PropertyActionKey propertyActionKey = new PropertyActionKey(propertyAction, methodSignature); this.mutableActions.put(propertyActionKey, template); this.actionsDispatcher.put(methodSignature, propertyActionKey); } this.order.add(name); this.mutableProperties.put(name, template); iterator.remove(); } if (methods.isEmpty()) { return; } if (sizeBefore == methods.size()) { throw new IllegalStateException("Can't create config template, can't find how to implement: " + methods); } this.scanMethods(methods, toKeyMappers, toStringMappers, knownProperties); }
Example 19
Source File: KafkaPool.java From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override public void heartbeatCheck(long timeout) { // 心跳 for (PhysicalNode physicalNode : physicalNodes.values()) { // 心跳检测, 超时抛弃 // -------------------------------------------------------------------------- long heartbeatTime = TimeUtil.currentTimeMillis() - timeout; long closeTime = TimeUtil.currentTimeMillis() - (timeout * 2); LinkedList<BackendConnection> heartBeatCons = getNeedHeartbeatCons(physicalNode.conQueue.getCons(), heartbeatTime, closeTime); if (!heartBeatCons.isEmpty()) { for (BackendConnection conn : heartBeatCons) { // apiKeyId、 version、 clientId、correlation int correlationId = Utils.getCorrelationId(); RequestHeader requestHeader = new RequestHeader(ApiKeys.API_VERSIONS.id, (short)1, CLIENT_ID, correlationId); Struct struct = requestHeader.toStruct(); int size = struct.sizeOf() + 4; // ByteBuffer buffer = NetSystem.getInstance().getBufferPool().allocate( size ); buffer.putInt(struct.sizeOf()); struct.writeTo(buffer); conHeartBeatHanler.doHeartBeat(conn, buffer); } } heartBeatCons.clear(); conHeartBeatHanler.abandTimeoutConns(); // 连接池 动态调整逻辑 // ------------------------------------------------------------------------------- int idleCons = physicalNode.getIdleCount(); int activeCons = physicalNode.getActiveCount(); int minCons = poolCfg.getMinCon(); int maxCons = poolCfg.getMaxCon(); if (LOGGER.isDebugEnabled()) LOGGER.debug("ClusterHeartbeat: host={}, idle={}, active={}, min={}, max={}, lasttime={}", new Object[] { physicalNode.getHost() + ":" + physicalNode.getPort(), idleCons, activeCons, minCons, maxCons, System.currentTimeMillis() }); if (idleCons > minCons) { if (idleCons < activeCons) { return; } // 闲置太多 closeByIdleMany(physicalNode, idleCons - minCons); } else if (idleCons < minCons) { if (idleCons > (minCons * 0.5)) { return; } // 闲置太少 if ((idleCons + activeCons) < maxCons) { int createCount = (int) Math.ceil((minCons - idleCons) / 3F); createByIdleLitte(physicalNode, idleCons, createCount); } } } }
Example 20
Source File: FastExtendedPostdominanceHelper.java From JByteMod-Beta with GNU General Public License v2.0 | 2 votes |
private void filterOnDominance(DominatorTreeExceptionFilter filter) { DominatorEngine engine = filter.getDomEngine(); for (Integer head : new HashSet<>(mapExtPostdominators.keySet())) { FastFixedSet<Integer> setPostdoms = mapExtPostdominators.get(head); LinkedList<Statement> stack = new LinkedList<>(); LinkedList<FastFixedSet<Integer>> stackPath = new LinkedList<>(); stack.add(statement.getStats().getWithKey(head)); stackPath.add(factory.spawnEmptySet()); Set<Statement> setVisited = new HashSet<>(); setVisited.add(stack.getFirst()); while (!stack.isEmpty()) { Statement stat = stack.removeFirst(); FastFixedSet<Integer> path = stackPath.removeFirst(); if (setPostdoms.contains(stat.id)) { path.add(stat.id); } if (path.contains(setPostdoms)) { continue; } if (!engine.isDominator(stat.id, head)) { setPostdoms.complement(path); continue; } for (StatEdge edge : stat.getSuccessorEdges(StatEdge.TYPE_REGULAR)) { Statement edge_destination = edge.getDestination(); if (!setVisited.contains(edge_destination)) { stack.add(edge_destination); stackPath.add(path.getCopy()); setVisited.add(edge_destination); } } } if (setPostdoms.isEmpty()) { mapExtPostdominators.remove(head); } } }