Java Code Examples for java.util.ArrayList

The following examples show how to use java.util.ArrayList. These examples are extracted from open source projects. 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 Project: netbeans   Source File: GrailsCommandChooser.java    License: Apache License 2.0 8 votes vote down vote up
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 Project: mireka   Source File: InjectableObjectContainer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: kourami   Source File: HLAGraph.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 4
Source Project: openjdk-jdk8u   Source File: DocumentImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 5
Source Project: pitest   Source File: ClassPath.java    License: Apache License 2.0 6 votes vote down vote up
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 6
Source Project: Bop   Source File: PlaylistUtils.java    License: Apache License 2.0 6 votes vote down vote up
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 7
@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 8
Source Project: BigDataScript   Source File: ValueList.java    License: Apache License 2.0 6 votes vote down vote up
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 9
Source Project: AnalyzeSkeleton   Source File: EdgeTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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 10
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 11
@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 12
Source Project: lams   Source File: FormulaParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 Project: netbeans   Source File: RestWrapperForSoapGenerator.java    License: Apache License 2.0 6 votes vote down vote up
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 14
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 15
Source Project: threadly   Source File: InternalFutureUtils.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@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 16
Source Project: gemfirexd-oss   Source File: DAPHelper.java    License: Apache License 2.0 6 votes vote down vote up
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 17
Source Project: ng-closure-runner   Source File: NgClosureRunner.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
  boolean minerrPass = false;
  String minerrErrors = "errors.json";
  String minerrUrl = null;
  String minerrSeparator = "/";
  String minerrJsResourcePath = "minErr.js";
  List<String> passthruArgs = new ArrayList<String>();

  for (int i = 0; i < args.length; i++) {
    String arg = args[i];
    if (arg.equals("--minerr_pass")) {
      minerrPass = true;
    } else if (arg.equals("--minerr_errors")) {
      minerrErrors = args[++i];
    } else if (arg.equals("--minerr_url")) {
      minerrUrl = args[++i];
    } else if (arg.equals("--minerr_separate_with_colon")) {
      minerrSeparator = ":";
    } else if (arg.equals("--minerr_js_resource_path")) {
      minerrJsResourcePath = args[++i];
    } else {
      passthruArgs.add(arg);
    }
  }

  NgClosureRunner runner = new NgClosureRunner(
      passthruArgs.toArray(new String[]{}),
      minerrPass, minerrErrors, minerrUrl, minerrSeparator,
      minerrJsResourcePath);

  if (runner.shouldRunCompiler()) {
    runner.run();
  } else {
    System.exit(-1);
  }
}
 
Example 18
Source Project: blynk-server   Source File: UserDao.java    License: GNU General Public License v3.0 5 votes vote down vote up
public List<User> searchByUsername(String name, String appName) {
    if (name == null) {
        return new ArrayList<>(users.values());
    }

    return users.values().stream().filter(user -> user.email.contains(name)
            && (appName == null || user.appName.equals(appName))).collect(Collectors.toList());
}
 
Example 19
Source Project: chronos   Source File: WithSql.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public List<JobSpec> getChildren(long id)
  throws BackendException {
  List<JobSpec> toRet = new ArrayList<>();
  Connection conn = null;
  PreparedStatement stat = null;
  try {
    conn = newConnection();
    stat =
      conn.prepareStatement(
        String.format("SELECT a.* FROM %s a " +
          "INNER JOIN " +
          "(SELECT id, MAX(lastModified) AS MaxModified " +
          "FROM %s " +
          "GROUP BY id) b " +
          "ON a.id = b.id " +
          "AND a.lastModified = b.MaxModified " +
          "WHERE a.parent = ? " +
          "ORDER BY a.name ASC", jobTableName, jobTableName));
    int i = 1;
    stat.setLong(i++, id);
    ResultSet rs = stat.executeQuery();
    while (rs != null && rs.next()) {
      toRet.add(parseJob(rs));
    }
    rs.close();
  } catch (SQLException ex) {
    throw new BackendException(ex);
  } finally {
    closeConnections(conn, stat);
  }
  return toRet;
}
 
Example 20
Source Project: redis-quartz   Source File: RedisJobStore.java    License: MIT License 5 votes vote down vote up
@Override
public List<String> getJobGroupNames() throws JobPersistenceException {
     try (Jedis jedis = pool.getResource()) {
        lockPool.acquire();
        return new ArrayList<>(jedis.smembers(JOB_GROUPS_SET));
	} catch(Exception ex) {
		throw new JobPersistenceException(ex.getMessage(), ex.getCause());
	} finally {
        lockPool.release();
	}		
}
 
Example 21
/**
 * add item to ipList
 *
 * @param ipList
 */
public void addIpList(String ipList) {
    if (this.ipList == null) {
        this.ipList = new ArrayList<>();
    }
    this.ipList.add(ipList);
}
 
Example 22
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (holder.getItemViewType() == 0) {
        ArrayList<ThemeDescription> arrayList = items.get(position - 1);
        ThemeDescription description = arrayList.get(0);
        int color;
        if (description.getCurrentKey().equals(Theme.key_chat_wallpaper)) {
            color = 0;
        } else {
            color = description.getSetColor();
        }
        ((TextColorThemeCell) holder.itemView).setTextAndColor(description.getTitle(), color);
    }
}
 
Example 23
Source Project: jig   Source File: PackageDepth.java    License: Apache License 2.0 5 votes vote down vote up
public List<PackageDepth> surfaceList() {
    ArrayList<PackageDepth> list = new ArrayList<>();
    for (int i = value; i >= 0; i--) {
        list.add(new PackageDepth(i));
    }
    return list;
}
 
Example 24
Source Project: Telegram   Source File: ContactsController.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void setPrivacyRules(ArrayList<TLRPC.PrivacyRule> rules, int type) {
    switch (type) {
        case PRIVACY_RULES_TYPE_LASTSEEN:
            lastseenPrivacyRules = rules;
            break;
        case PRIVACY_RULES_TYPE_INVITE:
            groupPrivacyRules = rules;
            break;
        case PRIVACY_RULES_TYPE_CALLS:
            callPrivacyRules = rules;
            break;
        case PRIVACY_RULES_TYPE_P2P:
            p2pPrivacyRules = rules;
            break;
        case PRIVACY_RULES_TYPE_PHOTO:
            profilePhotoPrivacyRules = rules;
            break;
        case PRIVACY_RULES_TYPE_FORWARDS:
            forwardsPrivacyRules = rules;
            break;
        case PRIVACY_RULES_TYPE_PHONE:
            phonePrivacyRules = rules;
            break;
        case PRIVACY_RULES_TYPE_ADDED_BY_PHONE:
            addedByPhonePrivacyRules = rules;
            break;
    }
    getNotificationCenter().postNotificationName(NotificationCenter.privacyRulesUpdated);
    reloadContactsStatuses();
}
 
Example 25
Source Project: webauthndemo   Source File: SessionData.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Load all sessions from datastore for a particular user.
 * 
 * @param currentUser
 * @return
 */
public static List<SessionData> load(String currentUser) {
  List<Entity> sessionEntities = loadEntities(currentUser);

  ArrayList<SessionData> sessions = new ArrayList<>();
  for (Entity e : sessionEntities) {
    SessionData session =
        new SessionData(BaseEncoding.base64().decode((String) e.getProperty(CHALLENGE_PROPERTY)),
            (String) e.getProperty(ORIGIN_PROPERTY), (Date) e.getProperty(TIMESTAMP_PROPERTY));
    sessions.add(session);
  }

  return sessions;
}
 
Example 26
@Override
protected List<TemporalField> invalidFields() {
    List<TemporalField> list = new ArrayList<TemporalField>(Arrays.<TemporalField>asList(ChronoField.values()));
    list.removeAll(validFields());
    list.add(JulianFields.JULIAN_DAY);
    list.add(JulianFields.MODIFIED_JULIAN_DAY);
    list.add(JulianFields.RATA_DIE);
    return list;
}
 
Example 27
Source Project: PackageTemplates   Source File: ExportHelper.java    License: Apache License 2.0 5 votes vote down vote up
public Context(Project project, String pathDir, PackageTemplateWrapper ptWrapper, HashSet<String> hsFileTemplateNames) {
    this.project = project;
    this.pathDir = pathDir;
    this.ptWrapper = ptWrapper;
    this.hsFileTemplateNames = hsFileTemplateNames;

    listSimpleAction = new ArrayList<>();
}
 
Example 28
Source Project: olat   Source File: FileSelection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks if there is at least one file with invalid file name in the selection. Returns the list with the invalid filenames.
 * 
 * @return
 */
public List getInvalidFileNames() {
    List invalidFileNames = new ArrayList();
    List filesList = getFiles();
    Iterator fileIterator = filesList.iterator();
    while (fileIterator.hasNext()) {
        String fileName = (String) fileIterator.next();
        if (!FileNameValidator.validate(fileName)) {
            invalidFileNames.add(fileName);
        }
    }
    return invalidFileNames;
}
 
Example 29
Source Project: JustDraw   Source File: JustView.java    License: MIT License 5 votes vote down vote up
public void draw(ArrayList<AbstractDraw> abstractDrawList) {
    mBitmap = Bitmap.createBitmap((int)mCanvasWidth, (int)mCanvasHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas();
    canvas.setBitmap(mBitmap);

    for (AbstractDraw abstractDraw : abstractDrawList) {
        abstractDraw.draw(canvas);
    }

    bDrawFinished = true;
}
 
Example 30
Source Project: gcs   Source File: Skill.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void prepareForLoad(LoadState state) {
    super.prepareForLoad(state);
    mName = getLocalizedName();
    mSpecialization = "";
    mTechLevel = null;
    mAttribute = SkillAttribute.DX;
    mDifficulty = SkillDifficulty.A;
    mPoints = 1;
    mReference = "";
    mEncumbrancePenaltyMultiplier = 0;
    mWeapons = new ArrayList<>();
}