Example usage for java.util ArrayList trimToSize

List of usage examples for java.util ArrayList trimToSize

Introduction

In this page you can find the example usage for java.util ArrayList trimToSize.

Prototype

public void trimToSize() 

Source Link

Document

Trims the capacity of this ArrayList instance to be the list's current size.

Usage

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

private Position buildPosition(final Node son, final Map<String, Object> env)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    if (positionClass == null) {
        L.error("position class not yet defined.");
    } else {/*  w ww .  j a  v  a  2  s  .  c  o m*/
        final NamedNodeMap attributes = son.getAttributes();
        final Node posNode = attributes.getNamedItem("position");
        if (posNode == null) {
            L.warn("a node has no position!");
        } else {
            final String args = posNode.getNodeValue();
            final StringTokenizer tk = new StringTokenizer(args, " ,;");
            final ArrayList<String> arguments = new ArrayList<String>();
            while (tk.hasMoreElements()) {
                arguments.add(tk.nextToken());
            }
            arguments.trimToSize();
            final List<Constructor<Position>> list = unsafeExtractConstructors(positionClass);
            return tryToBuild(list, arguments, env, random);
        }
    }
    return null;
}

From source file:org.getobjects.eocontrol.EOQualifier.java

/**
 * Filters a collection by applying the qualifier on each item. Only items
 * matching the qualifier will be included in the resulting List.
 * //from   w w w.j  ava  2  s  .  c o m
 * @param _in - the Collection to be filtered
 * @return a List of objects matching the qualifier 
 */
public List filterCollection(final Collection _in) {
    if (_in == null)
        return null;

    final EOQualifierEvaluation eval = (EOQualifierEvaluation) this;
    final ArrayList<Object> result = new ArrayList<Object>(_in.size());
    for (Object item : _in) {
        if (eval.evaluateWithObject(item))
            result.add(item);
    }

    result.trimToSize();
    return result;
}

From source file:com.silverwrist.venice.conf.impl.ConferenceManager.java

public List getConferences(DynamoUser user, VeniceCommunity comm) throws DatabaseException {
    boolean show_hidden = false;
    try { // do we want to show hidden conferences?
        show_hidden = comm.getAcl().testPermission(user, ConfNamespaces.PERMISSIONS_NAMESPACE, "see.hidden");

    } // end try/*from ww w.  j a  v  a2  s .  com*/
    catch (AclNotFoundException e) { // convert the AclNotFoundException
        DatabaseException de = new DatabaseException(ConferenceManager.class, "ConferenceMessages",
                "no.community.acl", e);
        de.setParameter(0, comm.getName());
        throw de;

    } // end catch

    List in_list = m_ops.getConferences(comm.getCID());
    if (in_list.isEmpty())
        return Collections.EMPTY_LIST;

    ArrayList rc = new ArrayList();
    Iterator it = in_list.iterator();
    while (it.hasNext()) { // get each data element and convert it
        Map d = (Map) (it.next());
        if (show_hidden || !(((Boolean) (d.get(ConferenceManagerOps.KEY_HIDE))).booleanValue())) { // skip hidden conferences if we don't have the "show hidden" permission
            ConferenceImpl conf = loadConference(d);
            rc.add(new LinkedConferenceImpl(m_ops.getLinkedConferenceOps(), conf, comm, m_srm, d));

        } // end if

    } // end while

    if (rc.isEmpty())
        return Collections.EMPTY_LIST;
    rc.trimToSize();
    return Collections.unmodifiableList(rc);

}

From source file:org.richfaces.component.UIOrderingBaseComponent.java

protected Object createContainer(ArrayList data, Object object) {
    if (object != null) {
        Class objectClass = object.getClass();
        Class componentType = objectClass.getComponentType();
        if (componentType != null) {
            return data.toArray((Object[]) Array.newInstance(componentType, data.size()));
        }//w  w w .ja  va2 s .  c om
    }

    data.trimToSize();
    return data;
}

From source file:org.zaproxy.zap.extension.formhandler.FormHandlerParam.java

@ZapApiIgnore
public void setFields(List<FormHandlerParamField> fields) {
    this.fields = new ArrayList<>(fields);

    ((HierarchicalConfiguration) getConfig()).clearTree(ALL_TOKENS_KEY);

    ArrayList<String> enabledFields = new ArrayList<>(fields.size());
    for (int i = 0, size = fields.size(); i < size; ++i) {
        String elementBaseKey = ALL_TOKENS_KEY + "(" + i + ").";
        FormHandlerParamField field = fields.get(i);

        getConfig().setProperty(elementBaseKey + TOKEN_NAME_KEY, field.getName().toLowerCase());
        getConfig().setProperty(elementBaseKey + TOKEN_VALUE_KEY, field.getValue());
        getConfig().setProperty(elementBaseKey + TOKEN_ENABLED_KEY, Boolean.valueOf(field.isEnabled()));

        if (field.isEnabled()) {
            enabledFields.add(field.getName().toLowerCase());
        }//from w  w w .j a  va 2s  .c o m
    }

    enabledFields.trimToSize();
    this.enabledFieldsNames = enabledFields;
}

From source file:com.joliciel.lefff.LefffDaoImpl.java

@Override
public Map<String, List<LexicalEntry>> findEntryMap(List<String> categories) {
    NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate(this.getDataSource());
    String sql = "SELECT " + SELECT_ENTRY + "," + SELECT_WORD + "," + SELECT_LEMMA + "," + SELECT_CATEGORY + ","
            + SELECT_PREDICATE + "," + SELECT_ATTRIBUTE + " FROM lef_entry"
            + " INNER JOIN lef_word ON entry_word_id = word_id"
            + " INNER JOIN lef_lemma ON entry_lemma_id = lemma_id"
            + " INNER JOIN lef_category ON entry_category_id = category_id"
            + " INNER JOIN lef_predicate ON entry_predicate_id = predicate_id"
            + " INNER JOIN lef_attribute ON entry_morph_id = attribute_id" + " WHERE entry_status < 3";

    if (categories != null && categories.size() > 0) {
        sql += " AND category_code in (:categoryCodes)";
    }/* ww  w.  j a  v  a 2  s.c o m*/

    sql += " ORDER BY entry_status, entry_id";
    MapSqlParameterSource paramSource = new MapSqlParameterSource();

    if (categories != null && categories.size() > 0) {
        paramSource.addValue("categoryCodes", categories);
    }
    LOG.info(sql);
    LefffDaoImpl.LogParameters(paramSource);
    double requiredCapacity = 500000;
    Map<String, List<LexicalEntry>> entryMap = new HashMap<String, List<LexicalEntry>>(
            ((int) Math.ceil(requiredCapacity / 0.75)));
    EntryMapper entryMapper = new EntryMapper(this.lefffServiceInternal);
    WordMapper wordMapper = new WordMapper(this.lefffServiceInternal);
    CategoryMapper categoryMapper = new CategoryMapper(this.lefffServiceInternal);
    LemmaMapper lemmaMapper = new LemmaMapper(this.lefffServiceInternal);
    PredicateMapper predicateMapper = new PredicateMapper(this.lefffServiceInternal);
    AttributeMapper attributeMapper = new AttributeMapper(this.lefffServiceInternal);
    SqlRowSet rowSet = jt.queryForRowSet(sql, paramSource);

    Map<Integer, Category> categoryMap = new HashMap<Integer, Category>();
    Map<Integer, Predicate> predicateMap = new HashMap<Integer, Predicate>();
    Map<Integer, Attribute> attributeMap = new HashMap<Integer, Attribute>();
    Map<Integer, Lemma> lemmaMap = new HashMap<Integer, Lemma>();

    while (rowSet.next()) {
        LefffEntryInternal entry = entryMapper.mapRow(rowSet);
        WordInternal word = wordMapper.mapRow(rowSet);
        entry.setWord(word);

        int categoryId = rowSet.getInt("category_id");
        Category category = categoryMap.get(categoryId);
        if (category == null) {
            category = categoryMapper.mapRow(rowSet);
            categoryMap.put(categoryId, category);
        }
        entry.setCategory(category);

        int predicateId = rowSet.getInt("predicate_id");
        Predicate predicate = predicateMap.get(predicateId);
        if (predicate == null) {
            predicate = predicateMapper.mapRow(rowSet);
            predicateMap.put(predicateId, predicate);
        }
        entry.setPredicate(predicate);

        int lemmaId = rowSet.getInt("lemma_id");
        Lemma lemma = lemmaMap.get(lemmaId);
        if (lemma == null) {
            lemma = lemmaMapper.mapRow(rowSet);
            lemmaMap.put(lemmaId, lemma);
        }
        entry.setLemma(lemma);

        int attributeId = rowSet.getInt("attribute_id");
        Attribute attribute = attributeMap.get(attributeId);
        if (attribute == null) {
            attribute = attributeMapper.mapRow(rowSet);
            attributeMap.put(attributeId, attribute);
        }
        entry.setMorphology(attribute);

        List<LexicalEntry> entries = entryMap.get(word.getText());
        if (entries == null) {
            entries = new ArrayList<LexicalEntry>();
            entryMap.put(word.getText(), entries);
        }
        entries.add(entry);
    }

    for (String word : entryMap.keySet()) {
        List<LexicalEntry> entries = entryMap.get(word);
        ArrayList<LexicalEntry> entriesArrayList = (ArrayList<LexicalEntry>) entries;
        entriesArrayList.trimToSize();
    }
    return entryMap;
}

From source file:org.polymap.core.data.feature.DataSourceProcessor.java

protected void getFeatures(FeatureSource fs, Query query, ProcessorContext context) throws Exception {
    log.debug("            Filter: " + query.getFilter());
    FeatureCollection fc = fs.getFeatures(query);

    Iterator it = null;//  w  ww  . ja v a 2 s.  co m
    int currentChunkSize = 64;
    try {
        ArrayList<Feature> chunk = new ArrayList(currentChunkSize);
        for (it = fc.iterator(); it.hasNext();) {
            Feature feature = (Feature) it.next();

            chunk.add(feature);
            if (chunk.size() >= currentChunkSize) {
                log.debug("                sending chunk: " + chunk.size());
                context.sendResponse(new GetFeaturesResponse(chunk));

                currentChunkSize = Math.min(DEFAULT_CHUNK_SIZE, currentChunkSize * 2);
                chunk = new ArrayList(currentChunkSize);
            }
        }
        if (!chunk.isEmpty()) {
            chunk.trimToSize();
            log.debug("                sending chunk: " + chunk.size());
            context.sendResponse(new GetFeaturesResponse(chunk));
        }
    } finally {
        if (it != null) {
            fc.close(it);
        }
    }
}

From source file:org.zaproxy.zap.extension.spiderAjax.AjaxSpiderParam.java

protected void setElems(List<AjaxSpiderParamElem> elems) {
    this.elems = new ArrayList<>(elems);

    ((HierarchicalConfiguration) getConfig()).clearTree(ALL_ELEMS_KEY);

    ArrayList<String> enabledElems = new ArrayList<>(elems.size());
    for (int i = 0, size = elems.size(); i < size; ++i) {
        String elementBaseKey = ALL_ELEMS_KEY + "(" + i + ").";
        AjaxSpiderParamElem elem = elems.get(i);

        getConfig().setProperty(elementBaseKey + ELEM_NAME_KEY, elem.getName());
        getConfig().setProperty(elementBaseKey + ELEM_ENABLED_KEY, Boolean.valueOf(elem.isEnabled()));

        if (elem.isEnabled()) {
            enabledElems.add(elem.getName());
        }//w w w  .  j  a  v  a  2 s  .co m
    }

    enabledElems.trimToSize();
    this.enabledElemsNames = enabledElems;
}

From source file:org.parosproxy.paros.db.TableHistory.java

/**
 * Gets all the history record IDs of the given session and with the given history types.
 *
 * @param sessionId the ID of session of the history records
 * @param histTypes the history types of the history records that should be returned
 * @return a {@code List} with all the history IDs of the given session and history types, never {@code null}
 * @throws SQLException if an error occurred while getting the history IDs
 * @since 2.3.0/*from   w  w w .  j a va2s . c  o m*/
 * @see #getHistoryIds(long)
 * @see #getHistoryIdsExceptOfHistType(long, int...)
 */
public List<Integer> getHistoryIdsOfHistType(long sessionId, int... histTypes) throws SQLException {
    boolean hasHistTypes = histTypes != null && histTypes.length > 0;
    int strLength = hasHistTypes ? 97 : 68;
    StringBuilder strBuilder = new StringBuilder(strLength);
    strBuilder.append("SELECT ").append(HISTORYID);
    strBuilder.append(" FROM ").append(TABLE_NAME).append(" WHERE ").append(SESSIONID).append(" = ?");
    if (hasHistTypes) {
        strBuilder.append(" AND ").append(HISTTYPE).append(" IN ( UNNEST(?) )");
    }
    strBuilder.append(" ORDER BY ").append(HISTORYID);

    try (PreparedStatement psReadSession = getConnection().prepareStatement(strBuilder.toString())) {

        psReadSession.setLong(1, sessionId);
        if (hasHistTypes) {
            Array arrayHistTypes = getConnection().createArrayOf("INTEGER", ArrayUtils.toObject(histTypes));
            psReadSession.setArray(2, arrayHistTypes);
        }
        try (ResultSet rs = psReadSession.executeQuery()) {
            ArrayList<Integer> ids = new ArrayList<>();
            while (rs.next()) {
                ids.add(Integer.valueOf(rs.getInt(HISTORYID)));
            }
            ids.trimToSize();

            return ids;
        }
    }
}

From source file:org.parosproxy.paros.db.TableHistory.java

/**
 * Returns all the history record IDs of the given session except the ones with the given history types.
 ** /*from   w  w  w.  j a  v  a  2  s .  c o m*/
 * @param sessionId the ID of session of the history records
 * @param histTypes the history types of the history records that should be excluded
 * @return a {@code List} with all the history IDs of the given session and history types, never {@code null}
 * @throws SQLException if an error occurred while getting the history IDs
 * @since 2.3.0
 * @see #getHistoryIdsOfHistType(long, int...)
 */
public List<Integer> getHistoryIdsExceptOfHistType(long sessionId, int... histTypes) throws SQLException {
    boolean hasHistTypes = histTypes != null && histTypes.length > 0;
    int strLength = hasHistTypes ? 102 : 68;
    StringBuilder sb = new StringBuilder(strLength);
    sb.append("SELECT ").append(HISTORYID);
    sb.append(" FROM ").append(TABLE_NAME).append(" WHERE ").append(SESSIONID).append(" = ?");
    if (hasHistTypes) {
        sb.append(" AND ").append(HISTTYPE).append(" NOT IN ( UNNEST(?) )");
    }
    sb.append(" ORDER BY ").append(HISTORYID);

    try (PreparedStatement psReadSession = getConnection().prepareStatement(sb.toString())) {

        psReadSession.setLong(1, sessionId);
        if (hasHistTypes) {
            Array arrayHistTypes = getConnection().createArrayOf("INTEGER", ArrayUtils.toObject(histTypes));
            psReadSession.setArray(2, arrayHistTypes);
        }
        try (ResultSet rs = psReadSession.executeQuery()) {
            ArrayList<Integer> ids = new ArrayList<>();
            while (rs.next()) {
                ids.add(Integer.valueOf(rs.getInt(HISTORYID)));
            }
            ids.trimToSize();

            return ids;
        }
    }
}