java.util.ArrayList Java Examples
The following examples show how to use
java.util.ArrayList.
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: GrailsCommandChooser.java From netbeans with Apache License 2.0 | 9 votes |
private List<String> getStoredParams(GrailsCommand task) { if (task == null) { return Collections.<String>emptyList(); } final Map<GrailsCommand, ParameterContainer> tasksToParams = getTasksToParams(); if (tasksToParams == null) { return Collections.<String>emptyList(); } ParameterContainer stored = tasksToParams.get(task); if (stored == null) { return Collections.<String>emptyList(); } List<String> result = new ArrayList<String>(stored.getParams()); Collections.sort(result); return result; }
Example #2
Source File: InjectableObjectContainer.java From mireka with Apache License 2.0 | 7 votes |
/** * Returns the default object which is suitable for the specified type. * * @param type * The type for which a default object is requested. * @return The single suitable object which was found. * @throws IllegalArgumentException * if zero or more than one object has been registered which is * assignable to the specified type. */ public Object get(Class<?> type) throws IllegalArgumentException { List<Object> found = new ArrayList<>(); for (Object object : objects) { if (type.isAssignableFrom(object.getClass())) found.add(object); } if (found.size() > 1) throw new IllegalArgumentException( "More than one default object meets the type " + type + ": " + found); if (found.isEmpty()) throw new IllegalArgumentException( "There is no default object for the type " + type); return found.get(0); }
Example #3
Source File: DAPHelper.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
private static void setTidListArray(int size, int numWorkers) { tidListArray = new ArrayList[size]; ArrayList<Integer> seed = new ArrayList<Integer>(); for (int i=0; i<numWorkers; i++) seed.add(i); //all the avail tid int bucketSize = numWorkers/size; //how many tid in each list bucket if (bucketSize == 0) bucketSize++; for (int i=0; i<size-1; i++) { tidListArray[i] = new ArrayList<Integer>(); for (int j=0; j<bucketSize; j++) { if (seed.size()>0) tidListArray[i].add(seed.remove(SQLTest.random.nextInt(seed.size()))); } } tidListArray[size-1] = new ArrayList<Integer>(); tidListArray[size-1].addAll(seed); //for the last list bucket }
Example #4
Source File: InternalFutureUtils.java From threadly with Mozilla Public License 2.0 | 6 votes |
@Override protected List<ListenableFuture<? extends T>> getFinalResultList() { List<ListenableFuture<? extends T>> superResult = super.getFinalResultList(); for (int i = 0; i < superResult.size(); i++) { // should be RandomAccess list if (superResult.get(i) == null) { // indicates we must manipulate list for (i = i == 0 ? 1 : 0; i < superResult.size(); i++) { if (superResult.get(i) != null) { // found first item that must be included ArrayList<ListenableFuture<? extends T>> result = new ArrayList<>(superResult.size() - Math.max(i, 1)); for (; i < superResult.size(); i++) { ListenableFuture<? extends T> lf = superResult.get(i); if (lf != null) { result.add(lf); } } return result; } } return Collections.emptyList(); // all items were null } } return superResult; // no null found }
Example #5
Source File: HLAGraph.java From kourami with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void removeUnusedEdges(){ Iterator<CustomWeightedEdge> itr = this.g.edgeSet().iterator(); CustomWeightedEdge e = null; ArrayList<CustomWeightedEdge> removalList = new ArrayList<CustomWeightedEdge>(); while(itr.hasNext()){ e = itr.next(); if(this.g.getEdgeWeight(e) < 1.0d){ removalList.add(e);//this.g.removeEdge(e); } } HLA.log.appendln(this.HLAGeneName +"\t:removed\t" + removalList.size() + "\tEdges." ); for(int i=0; i<removalList.size(); i++){ this.g.removeEdge(removalList.get(i)); } }
Example #6
Source File: ValueList.java From BigDataScript with Apache License 2.0 | 6 votes |
public void setValue(long idx, Value value) { ArrayList<Value> list = (ArrayList<Value>) this.list; int iidx = (int) idx; if (idx < 0) throw new RuntimeException("Cannot set list element indexed with negative index value: " + idx); // Make sure the array is big enough to hold the data if (iidx >= list.size()) { list.ensureCapacity(iidx + 1); Type elemType = ((TypeList) type).getElementType(); while (list.size() <= iidx) list.add(elemType.newDefaultValue()); } list.set((int) idx, value); }
Example #7
Source File: DocumentImpl.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
/** * Create and return a NodeIterator. The NodeIterator is * added to a list of NodeIterators so that it can be * removed to free up the DOM Nodes it references. * * @param root The root of the iterator. * @param whatToShow The whatToShow mask. * @param filter The NodeFilter installed. Null means no filter. * @param entityReferenceExpansion true to expand the contents of * EntityReference nodes * @since WD-DOM-Level-2-19990923 */ public NodeIterator createNodeIterator(Node root, int whatToShow, NodeFilter filter, boolean entityReferenceExpansion) { if (root == null) { String msg = DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_SUPPORTED_ERR", null); throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg); } NodeIterator iterator = new NodeIteratorImpl(this, root, whatToShow, filter, entityReferenceExpansion); if (iterators == null) { iterators = new ArrayList<>(); } iterators.add(iterator); return iterator; }
Example #8
Source File: GXDLMSPrimeNbOfdmPlcMacNetworkAdministrationData.java From gurux.dlms.java with GNU General Public License v2.0 | 6 votes |
private GXMacDirectTable[] loadDirectTable(GXXmlReader reader) throws XMLStreamException { List<GXMacDirectTable> list = new ArrayList<GXMacDirectTable>(); if (reader.isStartElement("DirectTable", true)) { while (reader.isStartElement("Item", true)) { GXMacDirectTable it = new GXMacDirectTable(); list.add(it); it.setSourceSId( (short) reader.readElementContentAsInt("SourceSId")); it.setSourceLnId( (short) reader.readElementContentAsInt("SourceLnId")); it.setSourceLcId( (short) reader.readElementContentAsInt("SourceLcId")); it.setDestinationSId((short) reader .readElementContentAsInt("DestinationSId")); it.setDestinationLnId((short) reader .readElementContentAsInt("DestinationLnId")); it.setDestinationLcId((short) reader .readElementContentAsInt("DestinationLcId")); it.setDid(GXCommon .hexToBytes(reader.readElementContentAsString("Did"))); } reader.readEndElement("DirectTable"); } return list.toArray(new GXMacDirectTable[list.size()]); }
Example #9
Source File: RestWrapperForSoapGenerator.java From netbeans with Apache License 2.0 | 6 votes |
private String[][] getHttpParamAnnotations(String[] paramTypeNames) { ArrayList<String[]> annos = new ArrayList<String[]>(); String[] annotations = null; if (!hasComplexTypes(paramTypeNames)) { for (int i = 0; i < paramTypeNames.length; i++) { Class type = getType(project, paramTypeNames[i]); if (generateDefaultValue(type) != null) { annotations = new String[]{ RestConstants.QUERY_PARAM, RestConstants.DEFAULT_VALUE }; } else { annotations = new String[]{RestConstants.QUERY_PARAM}; } annos.add(annotations); } } return annos.toArray(new String[annos.size()][]); }
Example #10
Source File: ClassPath.java From pitest with Apache License 2.0 | 6 votes |
private static List<ClassPathRoot> createRoots(final Collection<File> files) { File lastFile = null; try { final List<ClassPathRoot> rs = new ArrayList<>(); for (final File f : files) { lastFile = f; if (f.isDirectory()) { rs.add(new DirectoryClassPathRoot(f)); } else { handleArchive(rs, f); } } return rs; } catch (final IOException ex) { throw new PitError("Error handling file " + lastFile, ex); } }
Example #11
Source File: PlaylistUtils.java From Bop with Apache License 2.0 | 6 votes |
public static ArrayList<Song> getSongsByPlaylist(String playlistName) { ArrayList<Long> songIDs = new ArrayList<>(); for (Playlist playlist : Main.data.playlists) { if (playlist.getName().equals(playlistName)) { songIDs = playlist.getSongIds(); break; } } ArrayList<Song> currentSongs = new ArrayList<Song>(); if (songIDs != null) for (Long songID : songIDs) currentSongs.add(SongUtils.getSongById(songID)); Collections.sort(currentSongs, (song, t1) -> song.getTitle().compareTo(t1.getTitle())); return currentSongs; }
Example #12
Source File: FormulaParser.java From lams with GNU General Public License v2.0 | 6 votes |
private Object[] parseArrayRow() { List<Object> temp = new ArrayList<Object>(); while (true) { temp.add(parseArrayItem()); SkipWhite(); switch(look) { case '}': case ';': break; case ',': Match(','); continue; default: throw expected("'}' or ','"); } break; } Object[] result = new Object[temp.size()]; temp.toArray(result); return result; }
Example #13
Source File: ArrayListTypeFieldDeserializer.java From BigApp_Discuz_Android with Apache License 2.0 | 6 votes |
@SuppressWarnings("rawtypes") @Override public void parseField(DefaultJSONParser parser, Object object, Type objectType, Map<String, Object> fieldValues) { if (parser.getLexer().token() == JSONToken.NULL) { setValue(object, null); return; } ArrayList list = new ArrayList(); ParseContext context = parser.getContext(); parser.setContext(context, object, fieldInfo.getName()); parseArray(parser, objectType, list); parser.setContext(context); if (object == null) { fieldValues.put(fieldInfo.getName(), list); } else { setValue(object, list); } }
Example #14
Source File: FirebaseABTestingTest.java From firebase-android-sdk with Apache License 2.0 | 6 votes |
@Test public void replaceAllExperiments_noExperimentsInAnalytics_experimentsCorrectlySetInAnalytics() throws Exception { when(mockAnalyticsConnector.getConditionalUserProperties(ORIGIN_SERVICE, "")) .thenReturn(new ArrayList<>()); firebaseAbt.replaceAllExperiments( Lists.newArrayList( TEST_ABT_EXPERIMENT_1.toStringMap(), TEST_ABT_EXPERIMENT_2.toStringMap())); ArgumentCaptor<ConditionalUserProperty> analyticsExperimentArgumentCaptor = ArgumentCaptor.forClass(ConditionalUserProperty.class); verify(mockAnalyticsConnector, never()).clearConditionalUserProperty(any(), any(), any()); verify(mockAnalyticsConnector, times(2)) .setConditionalUserProperty(analyticsExperimentArgumentCaptor.capture()); List<ConditionalUserProperty> actualValues = analyticsExperimentArgumentCaptor.getAllValues(); AbtExperimentInfo analyticsExperiment1 = AbtExperimentInfo.fromConditionalUserProperty(actualValues.get(0)); AbtExperimentInfo analyticsExperiment2 = AbtExperimentInfo.fromConditionalUserProperty(actualValues.get(1)); // Validates that TEST_ABT_EXPERIMENT_1 and TEST_ABT_EXPERIMENT_2 have been set in Analytics. assertThat(analyticsExperiment1.toStringMap()).isEqualTo(TEST_ABT_EXPERIMENT_1.toStringMap()); assertThat(analyticsExperiment2.toStringMap()).isEqualTo(TEST_ABT_EXPERIMENT_2.toStringMap()); }
Example #15
Source File: WSDLDocument.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
public QName[] getPortQNames(String serviceNameLocalPart) { ArrayList portQNames = new ArrayList(); for (Iterator iter = getDefinitions().services(); iter.hasNext();) { Service next = (Service) iter.next(); if (next.getName().equals(serviceNameLocalPart)) { for (Iterator piter = next.ports(); piter.hasNext();) { Port pnext = (Port) piter.next(); String targetNamespace = pnext.getDefining().getTargetNamespaceURI(); String localName = pnext.getName(); QName portQName = new QName(targetNamespace, localName); portQNames.add(portQName); } } } return (QName[]) portQNames.toArray(new QName[portQNames.size()]); }
Example #16
Source File: EdgeTest.java From AnalyzeSkeleton with GNU General Public License v3.0 | 6 votes |
@Test public void testCloneUnconnected() throws Exception { final ArrayList<Point> slabs = new ArrayList<>(); slabs.add(new Point(1, 2, 3)); slabs.add(new Point(4, 5, 6)); final Edge edge = new Edge(null, null, slabs, 7.0, 8.0, 9.0, 10.0); edge.setType(11); final Edge clone = edge.clone(null, null); assertTrue(edge != clone); assertEquals(edge.getColor(), clone.getColor(), 1e-12); assertEquals(edge.getColor3rd(), clone.getColor3rd(), 1e-12); assertEquals(edge.getLength(), clone.getLength(), 1e-12); assertEquals(edge.getLength_ra(), clone.getLength_ra(), 1e-12); assertEquals(edge.getType(), clone.getType()); final ArrayList<Point> cloneSlabs = clone.getSlabs(); assertEquals(slabs.size(), cloneSlabs.size()); for (int i = 0; i < slabs.size(); i++) { assertEquals(slabs.get(i), cloneSlabs.get(i)); } }
Example #17
Source File: PathFinder.java From vividus with Apache License 2.0 | 5 votes |
@Override public List<String> findPaths(BatchResourceConfiguration batchResourceConfiguration) throws IOException { List<String> paths = new ArrayList<>(); process(batchResourceConfiguration, batchResourceConfiguration.getResourceIncludePatterns(), paths::add); process(batchResourceConfiguration, batchResourceConfiguration.getResourceExcludePatterns(), paths::remove); Collections.sort(paths); return paths; }
Example #18
Source File: AndroidPlacesApiJsonWriterTest.java From android-PlacesAutocompleteTextView with BSD 2-Clause "Simplified" License | 5 votes |
@Before public void setUp() throws IOException { parser = new AndroidPlacesApiJsonParser(); writer = mock(JsonWriter.class); actual = new ArrayList<>(); when(writer.beginArray()).then(new CompositeValueAnswer(BEGIN_ARRAY)); when(writer.endArray()).then(new CompositeValueAnswer(END_ARRAY)); when(writer.beginObject()).then(new CompositeValueAnswer(BEGIN_OBJECT)); when(writer.endObject()).then(new CompositeValueAnswer(END_OBJECT)); when(writer.value(anyInt())).then(new ValueAnswer()); when(writer.value(anyBoolean())).then(new ValueAnswer()); when(writer.value(anyString())).then(new ValueAnswer()); when(writer.name(anyString())).then(new ValueAnswer()); }
Example #19
Source File: ChannelTypeRegistry.java From smarthome with Eclipse Public License 2.0 | 5 votes |
/** * Returns all channel types for the given {@link Locale}. * * @param locale (can be null) * @return all channel types or empty list if no channel type exists */ public List<ChannelType> getChannelTypes(@Nullable Locale locale) { List<ChannelType> channelTypes = new ArrayList<>(); for (ChannelTypeProvider channelTypeProvider : channelTypeProviders) { channelTypes.addAll(channelTypeProvider.getChannelTypes(locale)); } return Collections.unmodifiableList(channelTypes); }
Example #20
Source File: Lexicogrphic_permutations.java From Algorithms with MIT License | 5 votes |
public static void sort(ArrayList<Integer> perms){ int index=0; while(index!=perms.size()){ int min=find_min(perms, index); swap(perms, index, min); } }
Example #21
Source File: CPlatformWindow.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
private void orderAboveSiblingsImpl(Window[] windows) { ArrayList<Window> childWindows = new ArrayList<Window>(); final ComponentAccessor componentAccessor = AWTAccessor.getComponentAccessor(); final WindowAccessor windowAccessor = AWTAccessor.getWindowAccessor(); // Go through the list of windows and perform ordering. for (Window w : windows) { boolean iconified = false; final Object p = componentAccessor.getPeer(w); if (p instanceof LWWindowPeer) { CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow(); iconified = isIconified(); if (pw != null && pw.isVisible() && !iconified) { // If the window is one of ancestors of 'main window' or is going to become main by itself, // the window should be ordered above its siblings; otherwise the window is just ordered // above its nearest parent. if (pw.isOneOfOwnersOrSelf(this)) { CWrapper.NSWindow.orderFront(pw.getNSWindowPtr()); } else { CWrapper.NSWindow.orderWindow(pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove, pw.owner.getNSWindowPtr()); } pw.applyWindowLevel(w); } } // Retrieve the child windows for each window from the list except iconified ones // and store them for future use. // Note: we collect data about child windows even for invisible owners, since they may have // visible children. if (!iconified) { childWindows.addAll(Arrays.asList(windowAccessor.getOwnedWindows(w))); } } // If some windows, which have just been ordered, have any child windows, let's start new iteration // and order these child windows. if (!childWindows.isEmpty()) { orderAboveSiblingsImpl(childWindows.toArray(new Window[0])); } }
Example #22
Source File: PostServiceImpl.java From FS-Blog with Apache License 2.0 | 5 votes |
@Override protected List<PostView> transEntityToView(List<Article> entityList) { List<PostView> postViewsList = new ArrayList<>(); Iterator it = entityList.iterator(); while (it.hasNext()) { Article article = (Article) it.next(); PostView postView = new PostView(article); postViewsList.add(postView); } return postViewsList; }
Example #23
Source File: ListManager.java From TickDynamic with MIT License | 5 votes |
public ListManager(World world, TickDynamicMod mod, EntityType type) { this.world = world; this.customProfiler = (CustomProfiler)world.theProfiler; this.mod = mod; this.entityType = type; localGroups = new HashSet<EntityGroup>(); groupMap = new HashMap<Class, EntityGroup>(); playerEntities = new ArrayList<EntityPlayer>(); queuedEntities = new ArrayDeque<EntityObject>(); entityCount = 0; age = 0; if(mod.debug) System.out.println("Initializing " + type + " list for world: " + world.provider.getDimensionName() + "(DIM" + world.provider.dimensionId + ")"); //Add groups from config loadLocalGroups(); loadGlobalGroups(); //Set default group for ungrouped if(type == EntityType.Entity) ungroupedEntities = mod.getWorldEntityGroup(world, "entity", type, false, false); else ungroupedEntities = mod.getWorldEntityGroup(world, "tileentity", type, false, false); if(ungroupedEntities == null || !localGroups.contains(ungroupedEntities) ) throw new RuntimeException("TickDynamic Assert failure: Could not find " + type + " group during world initialization!"); createGroupMap(); }
Example #24
Source File: CoreDensityMap.java From workcraft with MIT License | 5 votes |
private ArrayList<Integer> buidDensityPalette(Set<Integer> densitySet) { ArrayList<Integer> densityList = new ArrayList<>(densitySet); Collections.sort(densityList); int levelLimit = StgSettings.getDensityMapLevelLimit(); int fromIndex = (densityList.size() < levelLimit) ? 0 : densityList.size() - levelLimit; return new ArrayList<>(densityList.subList(fromIndex, densityList.size())); }
Example #25
Source File: BaseDaoMysqlImpl.java From Crawer with MIT License | 5 votes |
@Override public <E> List<E> search(String sql, List<Object> values, Class<E> e) { if (StringUtils.isEmpty(sql)) return new ArrayList<E>(); if (values == null) values = new ArrayList<Object>(); logger.info("sql : " + sql + " values:" + values); return this.getJdbcTemplate().query(sql, values.toArray(), new BeanPropertyRowMapper<E>(e)); }
Example #26
Source File: Loggers.java From unitime with Apache License 2.0 | 5 votes |
@Override @PreAuthorize("checkPermission('ApplicationConfig')") public SimpleEditInterface load(SessionContext context, Session hibSession) { List<ListItem> levels = new ArrayList<ListItem>(); levels.add(new ListItem(String.valueOf(Level.ALL_INT), MESSAGES.levelAll())); levels.add(new ListItem(String.valueOf(Level.TRACE_INT), MESSAGES.levelTrace())); levels.add(new ListItem(String.valueOf(Level.DEBUG_INT), MESSAGES.levelDebug())); levels.add(new ListItem(String.valueOf(Level.INFO_INT), MESSAGES.levelInfo())); levels.add(new ListItem(String.valueOf(Level.WARN_INT), MESSAGES.levelWarning())); levels.add(new ListItem(String.valueOf(Level.ERROR_INT), MESSAGES.levelError())); levels.add(new ListItem(String.valueOf(Level.FATAL_INT), MESSAGES.levelFatal())); levels.add(new ListItem(String.valueOf(Level.OFF_INT), MESSAGES.levelOff())); SimpleEditInterface data = new SimpleEditInterface( new Field(MESSAGES.fieldLogger(), FieldType.text, 400, 1024, Flag.UNIQUE), new Field(MESSAGES.fieldLevel(), FieldType.list, 100, levels, Flag.NOT_EMPTY)); data.setSortBy(0, 1); long id = 0; SimpleEditInterface.Record root = data.addRecord(id++, false); root.setField(0, " root", false); root.setField(1, String.valueOf(LogManager.getRootLogger().getLevel().toInt())); for (Enumeration e = LogManager.getCurrentLoggers(); e.hasMoreElements(); ) { Logger logger = (Logger)e.nextElement(); if (logger.getLevel() == null) continue; ApplicationConfig config = ApplicationConfig.getConfig("log4j.logger." + logger.getName()); SimpleEditInterface.Record record = data.addRecord(id++, ApplicationProperties.getDefaultProperties().getProperty("log4j.logger." + logger.getName()) == null && config != null); record.setField(0, logger.getName(), false); record.setField(1, String.valueOf(logger.getLevel().toInt())); } data.setEditable(context.hasPermission(Right.ApplicationConfig)); return data; }
Example #27
Source File: GridLayoutManager.java From TvRecyclerView with Apache License 2.0 | 5 votes |
public void setOnChildViewHolderSelectedListener(OnChildViewHolderSelectedListener listener) { if (listener == null) { mChildViewHolderSelectedListeners = null; return; } if (mChildViewHolderSelectedListeners == null) { mChildViewHolderSelectedListeners = new ArrayList<>(); } else { mChildViewHolderSelectedListeners.clear(); } mChildViewHolderSelectedListeners.add(listener); }
Example #28
Source File: NbestEvaluationAnnotation.java From phrasal with GNU General Public License v3.0 | 5 votes |
static public void main(String[] args) throws Exception { if (args.length < 4) { usage(); exit(-1); } String nbestFn = args[0]; String metricName = args[1]; String nbestOutFn = args[2]; String[] refFns = new String[args.length-3]; for (int i = 0; i < refFns.length; i++) { refFns[i] = args[i+3]; } FlatNBestList nbest = new FlatNBestList(nbestFn); List<List<Sequence<IString>>> refs= MetricUtils.readReferences( refFns); List<List<ScoredFeaturizedTranslation<IString,String>>> nbestLists = nbest.nbestLists(); PrintWriter nbestOut = new PrintWriter(new FileWriter(nbestOutFn)); for (int id = 0; id < nbestLists.size(); id++) { List<ScoredFeaturizedTranslation<IString, String>> nbestList = nbestLists.get(id); EvaluationMetric<IString,String> emetric = CorpusLevelMetricFactory.newMetric(metricName, refs.subList(id, id+1)); for (ScoredFeaturizedTranslation<IString, String> tran : nbestList) { List<ScoredFeaturizedTranslation<IString,String>> trans = new ArrayList<ScoredFeaturizedTranslation<IString,String>>(1); trans.add(tran); double emetricScore = emetric.score(trans); nbestOut.printf("%d ||| %s ||| %f\n", id, tran.toString(), emetricScore); } } nbestOut.close(); }
Example #29
Source File: ClusterTemplate.java From director-sdk with Apache License 2.0 | 5 votes |
public ClusterTemplate addPreTerminateScriptsItem(String preTerminateScriptsItem) { if (this.preTerminateScripts == null) { this.preTerminateScripts = new ArrayList<String>(); } this.preTerminateScripts.add(preTerminateScriptsItem); return this; }
Example #30
Source File: NavigationScene.java From scene with Apache License 2.0 | 5 votes |
@Override public void onFinish() { List<InteractionNavigationPopAnimationFactory.InteractionCallback> copy = new ArrayList<>(mInteractionListenerList); for (InteractionNavigationPopAnimationFactory.InteractionCallback callback : copy) { callback.onFinish(); } }