Java Code Examples for java.util.ArrayList#add()
The following examples show how to use
java.util.ArrayList#add() .
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: RenderUtils.java From jaamsim with Apache License 2.0 | 8 votes |
/** * Returns a list of points for a circle in the XY plane at the origin * @return */ public static ArrayList<Vec4d> getCirclePoints(int numSegments) { if (numSegments < 3) { return null; } ArrayList<Vec4d> ret = new ArrayList<>(); double thetaStep = 2 * Math.PI / numSegments; for (int i = 0; i < numSegments + 1; ++i) { double theta = i * thetaStep; ret.add(new Vec4d(Math.cos(theta), Math.sin(theta), 0, 1.0d)); } return ret; }
Example 2
Source File: OptionsFormatterTests.java From vscode-as3mxml with Apache License 2.0 | 6 votes |
@Test void testAppendPaths() { String optionName = "optionName"; String value1 = "path/to/file1.txt"; String value2 = "path/to/file2 with spaces.txt"; String value3 = "./path/to/file3.txt"; ArrayList<String> values = new ArrayList<>(); values.add(value1); values.add(value2); values.add(value3); ArrayList<String> result = new ArrayList<>(); OptionsFormatter.appendPaths(optionName, values, result); Assertions.assertEquals(3, result.size(), "OptionsFormatter.testAppendPaths() created incorrect number of options."); Assertions.assertEquals("--optionName+=" + value1, result.get(0), "OptionsFormatter.testAppendPaths() incorrectly formatted option."); Assertions.assertEquals("--optionName+=" + value2, result.get(1), "OptionsFormatter.testAppendPaths() incorrectly formatted option."); Assertions.assertEquals("--optionName+=" + value3, result.get(2), "OptionsFormatter.testAppendPaths() incorrectly formatted option."); }
Example 3
Source File: ExecutionJobVertex.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
/** * Schedules all execution vertices of this ExecutionJobVertex. * * @param slotProvider to allocate the slots from * @param queued if the allocations can be queued * @param locationPreferenceConstraint constraint for the location preferences * @param allPreviousExecutionGraphAllocationIds set with all previous allocation ids in the job graph. * Can be empty if the allocation ids are not required for scheduling. * @return Future which is completed once all {@link Execution} could be deployed */ public CompletableFuture<Void> scheduleAll( SlotProvider slotProvider, boolean queued, LocationPreferenceConstraint locationPreferenceConstraint, @Nonnull Set<AllocationID> allPreviousExecutionGraphAllocationIds) { final ExecutionVertex[] vertices = this.taskVertices; final ArrayList<CompletableFuture<Void>> scheduleFutures = new ArrayList<>(vertices.length); // kick off the tasks for (ExecutionVertex ev : vertices) { scheduleFutures.add(ev.scheduleForExecution( slotProvider, queued, locationPreferenceConstraint, allPreviousExecutionGraphAllocationIds)); } return FutureUtils.waitForAll(scheduleFutures); }
Example 4
Source File: TestSortingNetwork.java From angelix with MIT License | 6 votes |
@Test public void testAtMostTwo() { List<Selector> bits = new ArrayList<>(); bits.add(a); bits.add(b); bits.add(c); bits.add(d); ArrayList<Node> triples = new ArrayList<>(); for (Selector bit : bits) { List<Selector> newBits = new ArrayList<>(bits); newBits.remove(bit); triples.add(Node.conjunction(newBits)); } ArrayList<Node> clauses = new ArrayList<>(); clauses.add(Node.conjunction(triples)); clauses.addAll(Cardinality.SortingNetwork.atMostK(2, bits)); Optional<Map<Variable, Constant>> result = solver.sat(clauses); assertFalse(result.isPresent()); }
Example 5
Source File: DeployCoprocessorCLI.java From kylin-on-parquet-v2 with Apache License 2.0 | 6 votes |
private static List<String> getHTableNames(KylinConfig config) { CubeManager cubeMgr = CubeManager.getInstance(config); ArrayList<String> result = new ArrayList<String>(); for (CubeInstance cube : cubeMgr.listAllCubes()) { if (cube.getStorageType() == IStorageAware.ID_HBASE || cube.getStorageType() == IStorageAware.ID_SHARDED_HBASE || cube.getStorageType() == IStorageAware.ID_REALTIME_AND_HBASE) { for (CubeSegment seg : cube.getSegments(SegmentStatusEnum.READY)) { String tableName = seg.getStorageLocationIdentifier(); if (StringUtils.isBlank(tableName) == false) { result.add(tableName); System.out.println("added new table: " + tableName); } } } } return result; }
Example 6
Source File: SohuUserAdaptor.java From YiBo with Apache License 2.0 | 6 votes |
/** * 从JSON字符串创建User对象列表 * * @param jsonString * JSON字符串 * @return User对象列表 * @throws LibException */ public static List<User> createUserList(String jsonString) throws LibException { try { if ("[]".equals(jsonString) || "{}".equals(jsonString)) { return new PagableList<User>(0, 0, 0); } JSONArray jsonList = new JSONArray(jsonString); int size = jsonList.length(); ArrayList<User> userList = new ArrayList<User>(size); for (int i = 0; i < size; i++) { userList.add(createUser(jsonList.getJSONObject(i))); } return userList; } catch (JSONException e) { throw new LibException(LibResultCode.JSON_PARSE_ERROR); } }
Example 7
Source File: DataSetLabelBinarySeperator.java From CS-7641-assignments with MIT License | 6 votes |
public static void seperateLabels(DataSet set) { int numberOfLabels = 0; ArrayList<Integer> labels = new ArrayList<Integer>(); //count up the number of distinct labels for(int i = 0; i < set.size(); i++){ if(!labels.contains(new Integer(set.getInstances()[i].getLabel().getDiscrete()))){ numberOfLabels++; labels.add(new Integer(set.getInstances()[i].getLabel().getDiscrete())); } } double[] values = new double[numberOfLabels]; for(int i = 0; i < values.length; i++){ values[i] = 0; } for(int i = 0; i < set.size(); i++){ int labelValue = set.getInstances()[i].getLabel().getDiscrete()%values.length; values[labelValue] = 1; Instance instance = new Instance(Arrays.copyOf(values, values.length)); set.get(i).setLabel(instance); values[labelValue] = 0; } }
Example 8
Source File: JoinNode.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
protected static String[] getTableColumnDetails(ResultSetNode rs) throws StandardException { final ArrayList<String> tables = new ArrayList<String>(); VisitorAdaptor findLeftTables = new VisitorAdaptor() { @Override public Visitable visit(Visitable node) throws StandardException { if (node instanceof FromTable) { tables.add("{" + ((FromTable)node).getCorrelationName() + " " + ((FromTable)node).getOrigTableName() + "}"); } return node; } }; rs.accept(findLeftTables); String involvedTables = tables.toString(); String[] leftRSColumns = rs.resultColumns.getColumnNames(); String[] rsColumnsWithTables = new String[leftRSColumns.length + 1]; rsColumnsWithTables[0] = involvedTables; System.arraycopy(leftRSColumns, 0, rsColumnsWithTables, 1, leftRSColumns.length); return rsColumnsWithTables; }
Example 9
Source File: SchoolLevelTypeConverter.java From secure-data-service with Apache License 2.0 | 5 votes |
public List<String> convertAsList(SchoolLevelType schoolLevelType) { if (schoolLevelType == null) { return null; } ArrayList<String> list = new ArrayList<String>(); String category = SCHOOL_LEVEL_TYPE_MAP.get(schoolLevelType); if (category != null) { list.add(category); } return list; }
Example 10
Source File: AbstractQueuedSynchronizer.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
/** * Returns a collection containing threads that may be waiting to * acquire in exclusive mode. This has the same properties * as {@link #getQueuedThreads} except that it only returns * those threads waiting due to an exclusive acquire. * * @return the collection of threads */ public final Collection<Thread> getExclusiveQueuedThreads() { ArrayList<Thread> list = new ArrayList<Thread>(); for (Node p = tail; p != null; p = p.prev) { if (!p.isShared()) { Thread t = p.thread; if (t != null) list.add(t); } } return list; }
Example 11
Source File: LVRVActivity.java From LinkageScrollLayout with Apache License 2.0 | 5 votes |
private ArrayList<String> getLVData() { ArrayList<String> data = new ArrayList<>(); String temp = "ListView - "; for(int i = 0; i < 30; i++) { data.add(temp + i); } return data; }
Example 12
Source File: NGSIBatch.java From fiware-cygnus with GNU Affero General Public License v3.0 | 5 votes |
/** * Adds an event to the given destination sub-batch. * @param destination * @param event */ public void addEvent(String destination, NGSIEvent event) { SubBatch subBatch = subBatches.get(destination); if (subBatch == null) { ArrayList<NGSIEvent> events = new ArrayList<>(); events.add(event); subBatch = new SubBatch(false, events); subBatches.put(destination, subBatch); } else { subBatch.getEvents().add(event); } // if else numEvents++; }
Example 13
Source File: UiDocumentServiceImplTest.java From rice with Educational Community License v2.0 | 5 votes |
@Test public void testInactiveRoleMemberOnly() { KimType.Builder ktBuilder = KimType.Builder.create(); ktBuilder.setId("1"); ktBuilder.setNamespaceCode("KUALI"); ktBuilder.setName("Default"); Long version = new Long(1) ; ktBuilder.setVersionNumber(version); KimType kt = ktBuilder.build() ; IdentityManagementRoleDocument identityManagementRoleDocument = new IdentityManagementRoleDocument(); identityManagementRoleDocument.setKimType(kt); identityManagementRoleDocument.setRoleId("KRSAP10003"); identityManagementRoleDocument.setRoleTypeId("1"); identityManagementRoleDocument.setRoleName("Default"); identityManagementRoleDocument.setRoleNamespace("KR_SAP"); identityManagementRoleDocument.setRoleName("Sample App Admin"); RoleMemberBo roleMemberBo = new RoleMemberBo(); roleMemberBo.setId("KRSAP10003"); roleMemberBo.setRoleId("KRSAP1003"); roleMemberBo.setMemberId("dev1"); roleMemberBo.setTypeCode("P"); // make the role member inactive Timestamp timestamp = new Timestamp(System.currentTimeMillis()); roleMemberBo.setActiveToDateValue(timestamp); ArrayList<RoleMemberBo> roleMemberBos = new ArrayList<RoleMemberBo>(); roleMemberBos.add(roleMemberBo); // We've got one role member, and it is inactive. UiDocumentServiceImpl uiDocumentServiceImpl = new UiDocumentServiceImpl() ; List<KimDocumentRoleMember> kimDocumentRoleMembers = uiDocumentServiceImpl.loadRoleMembers(identityManagementRoleDocument, roleMemberBos); assertEquals("KimDocuemtnRoleMember size is incorrect", 0, kimDocumentRoleMembers.size()); }
Example 14
Source File: NewsAdapter.java From okhttp-OkGo with Apache License 2.0 | 5 votes |
@Override protected void convert(BaseViewHolder baseViewHolder, final GankModel model) { baseViewHolder.setText(R.id.title, model.desc)// .setText(R.id.desc, model.desc)// .setText(R.id.pubDate, model.publishedAt.toString())// .setText(R.id.source, model.source); View view = baseViewHolder.getConvertView(); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WebActivity.runActivity(mContext, model.desc, model.url); } }); NineGridView nineGrid = baseViewHolder.getView(R.id.nineGrid); ArrayList<ImageInfo> imageInfo = new ArrayList<>(); if (model.images != null) { for (String image : model.images) { ImageInfo info = new ImageInfo(); info.setThumbnailUrl(image); info.setBigImageUrl(image); imageInfo.add(info); } } nineGrid.setAdapter(new NineGridViewClickAdapter(mContext, imageInfo)); }
Example 15
Source File: TypeAnnotation.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
public TypeAnnotation[] filter(TypeAnnotation[] ta) { ArrayList<TypeAnnotation> l = new ArrayList<>(ta.length); for (TypeAnnotation t : ta) { if (isSameLocationInfo(t.getLocationInfo())) l.add(t); } return l.toArray(new TypeAnnotation[0]); }
Example 16
Source File: BradyBoundApplication.java From bradybound with GNU General Public License v3.0 | 5 votes |
private static Collection<String> getOutputUntil(BufferedReader ins, String stopLine) throws IOException { ArrayList<String> lines = new ArrayList<String>(); while (true) { String line = ins.readLine(); if (line == null || stopLine.equals(line)) break; lines.add(line); } return lines; }
Example 17
Source File: MergingSequence.java From incubator-retired-wave with Apache License 2.0 | 5 votes |
public void optimise() { int startSize = size(); if (startSize == 1) { return; } ArrayList<DocOp> docOps = CollectionUtils.newArrayList(); List<WaveletOperation> oldOperations = CollectionUtils.newArrayList(this); String currentId = null; WaveletOperationContext lastOperationContext = null; this.clear(); for (WaveletOperation waveletOp : oldOperations) { if (waveletOp instanceof WaveletBlipOperation) { WaveletBlipOperation waveletBlipOp = ((WaveletBlipOperation) waveletOp); String id = waveletBlipOp.getBlipId(); BlipOperation blipOp = waveletBlipOp.getBlipOp(); if (blipOp instanceof BlipContentOperation) { if (!docOps.isEmpty() && !id.equals(currentId)) { composeDocOps(this, currentId, lastOperationContext, docOps); } docOps.add(((BlipContentOperation) blipOp).getContentOp()); lastOperationContext = blipOp.getContext(); currentId = id; continue; } } if (!docOps.isEmpty()) { composeDocOps(this, currentId, lastOperationContext, docOps); } add(waveletOp); } if (!docOps.isEmpty()) { composeDocOps(this, currentId, lastOperationContext, docOps); } }
Example 18
Source File: UserDataDBHelper.java From IslamicLibraryAndroid with GNU General Public License v3.0 | 4 votes |
@NonNull public ArrayList<UserNoteItem> getBookmarkItems(Context context) throws IllegalArgumentException { // if (!order.equals(UserDataDBContract.BookmarkEntry.COLUMN_NAME_PAGE_ID) || // !order.equals(UserDataDBContract.BookmarkEntry.COLUMN_NAME_PAGE_ID)) { // throw new IllegalArgumentException("order must be {@link UserDataDBContract.BookmarkEntry.COLUMN_NAME_PAGE_ID} or" + // " UserDataDBContract.BookmarkEntry.COLUMN_NAME_TIME_STAMP}"); // // } ArrayList<UserNoteItem> bookmarksList = new ArrayList<>(); Cursor c = getReadableDatabase() .query(UserDataDBContract.BookmarkEntry.TABLE_NAME, new String[]{ UserDataDBContract.BookmarkEntry.COLUMN_NAME_BOOK_ID, UserDataDBContract.BookmarkEntry.COLUMN_NAME_PAGE_ID, UserDataDBContract.BookmarkEntry.COLUMN_NAME_TIME_STAMP}, null, null, null, null, UserDataDBContract.BookmarkEntry.COLUMN_NAME_PAGE_ID ); final int INDEX_BOOK_ID = c.getColumnIndex(UserDataDBContract.BookmarkEntry.COLUMN_NAME_BOOK_ID); final int INDEX_PAGE_ID = c.getColumnIndex(UserDataDBContract.BookmarkEntry.COLUMN_NAME_PAGE_ID); final int INDEX_TIME_STAMP = c.getColumnIndex(UserDataDBContract.BookmarkEntry.COLUMN_NAME_TIME_STAMP); BooksInformationDbHelper booksInformationDbHelper = BooksInformationDbHelper.getInstance(context); while (c.moveToNext()) { int bookId = c.getInt(INDEX_BOOK_ID); if (booksInformationDbHelper != null && booksInformationDbHelper.isBookDownloaded(bookId)) { try { BookDatabaseHelper bookDatabaseHelper = BookDatabaseHelper.getInstance(context, bookId); int pageId = c.getInt(INDEX_PAGE_ID); BookInfo bookInfo = bookDatabaseHelper.getBookInfo(); BookPartsInfo bookPartsInfo = bookDatabaseHelper.getBookPartsInfo(); PageInfo pageInfo = bookDatabaseHelper.getPageInfoByPageId(pageId); Bookmark bookmark = new Bookmark(bookId, pageInfo, c.getString(INDEX_TIME_STAMP), bookDatabaseHelper.getParentTitle(pageId)); bookmarksList.add(new BookmarkItem(bookmark, bookPartsInfo, bookInfo)); } catch (BookDatabaseException bookDatabaseException) { Timber.e(bookDatabaseException); } } } c.close(); return bookmarksList; }
Example 19
Source File: InputSampler.java From hadoop with Apache License 2.0 | 4 votes |
/** * Randomize the split order, then take the specified number of keys from * each split sampled, where each key is selected with the specified * probability and possibly replaced by a subsequently selected key when * the quota of keys from that split is satisfied. */ @SuppressWarnings("unchecked") // ArrayList::toArray doesn't preserve type public K[] getSample(InputFormat<K,V> inf, Job job) throws IOException, InterruptedException { List<InputSplit> splits = inf.getSplits(job); ArrayList<K> samples = new ArrayList<K>(numSamples); int splitsToSample = Math.min(maxSplitsSampled, splits.size()); Random r = new Random(); long seed = r.nextLong(); r.setSeed(seed); LOG.debug("seed: " + seed); // shuffle splits for (int i = 0; i < splits.size(); ++i) { InputSplit tmp = splits.get(i); int j = r.nextInt(splits.size()); splits.set(i, splits.get(j)); splits.set(j, tmp); } // our target rate is in terms of the maximum number of sample splits, // but we accept the possibility of sampling additional splits to hit // the target sample keyset for (int i = 0; i < splitsToSample || (i < splits.size() && samples.size() < numSamples); ++i) { TaskAttemptContext samplingContext = new TaskAttemptContextImpl( job.getConfiguration(), new TaskAttemptID()); RecordReader<K,V> reader = inf.createRecordReader( splits.get(i), samplingContext); reader.initialize(splits.get(i), samplingContext); while (reader.nextKeyValue()) { if (r.nextDouble() <= freq) { if (samples.size() < numSamples) { samples.add(ReflectionUtils.copy(job.getConfiguration(), reader.getCurrentKey(), null)); } else { // When exceeding the maximum number of samples, replace a // random element with this one, then adjust the frequency // to reflect the possibility of existing elements being // pushed out int ind = r.nextInt(numSamples); if (ind != numSamples) { samples.set(ind, ReflectionUtils.copy(job.getConfiguration(), reader.getCurrentKey(), null)); } freq *= (numSamples - 1) / (double) numSamples; } } } reader.close(); } return (K[])samples.toArray(); }
Example 20
Source File: UserHandlerV1.java From orion.server with Eclipse Public License 1.0 | 4 votes |
private boolean handleUsersGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, CoreException { List<String> users = getAllUsers(); String startParam = req.getParameter(START); String rowsParam = req.getParameter(ROWS); int start = 0, rows = 0, count = 0; if (startParam != null && !(startParam.length() == 0)) { start = Integer.parseInt(startParam); if (start < 0) { start = 0; } } else { start = 0; } if (rowsParam != null && !(rowsParam.length() == 0)) { rows = Integer.parseInt(rowsParam); if (rows < 0) { rows = 20; // default is to return 20 at a time } } else { // if there's no start and no rows then return the default first 20 users rows = 20; // default is to return 20 at a time } ArrayList<JSONObject> userJSONs = new ArrayList<JSONObject>(); URI location = ServletResourceHandler.getURI(req); for (String userId : users) { if (count >= start + rows) { break; } if (count++ < start) { continue; } URI userLocation = URIUtil.append(location, userId); UserInfo userInfo = OrionConfiguration.getMetaStore().readUser(userId); userJSONs.add(formJson(userInfo, userLocation, req.getContextPath())); } JSONObject json = new JSONObject(); json.put(USERS, userJSONs); json.put(USERS_START, start); json.put(USERS_ROWS, rows); json.put(USERS_LENGTH, users.size()); OrionServlet.writeJSONResponse(req, resp, json); return true; }