java.util.ArrayList#add ( )源码实例Demo

下面列出了java.util.ArrayList#add ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jaamsim   文件: RenderUtils.java
/**
 * 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;
}
 
源代码2 项目: vscode-as3mxml   文件: OptionsFormatterTests.java
@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.");
}
 
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;
	}
}
 
源代码4 项目: YiBo   文件: SohuUserAdaptor.java
/**
 * 从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);
	}
}
 
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;
}
 
源代码6 项目: angelix   文件: TestSortingNetwork.java
@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());
}
 
源代码7 项目: Flink-CEPplus   文件: ExecutionJobVertex.java
/**
 * 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);
}
 
源代码8 项目: okhttp-OkGo   文件: NewsAdapter.java
@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));
}
 
源代码9 项目: fiware-cygnus   文件: NGSIBatch.java
/**
 * 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++;
}
 
源代码10 项目: jdk8u_jdk   文件: AbstractQueuedSynchronizer.java
/**
 * 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;
}
 
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;
}
 
源代码12 项目: gemfirexd-oss   文件: JoinNode.java
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;
}
 
源代码13 项目: LinkageScrollLayout   文件: LVRVActivity.java
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;
}
 
源代码14 项目: rice   文件: UiDocumentServiceImplTest.java
@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());
}
 
源代码15 项目: openjdk-jdk8u-backup   文件: TypeAnnotation.java
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]);
}
 
源代码16 项目: bradybound   文件: BradyBoundApplication.java
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;
}
 
源代码17 项目: incubator-retired-wave   文件: MergingSequence.java
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);
  }
}
 
源代码18 项目: orion.server   文件: UserHandlerV1.java
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;
}
 
源代码19 项目: IslamicLibraryAndroid   文件: UserDataDBHelper.java
@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;
        }
 
源代码20 项目: hadoop   文件: InputSampler.java
/**
 * 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();
}