Example usage for java.util ArrayList ensureCapacity

List of usage examples for java.util ArrayList ensureCapacity

Introduction

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

Prototype

public void ensureCapacity(int minCapacity) 

Source Link

Document

Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

Usage

From source file:edu.scripps.fl.pubchem.EUtilsFactory.java

public List<Relation> getRelations(Document document) {
    String fromDb = document.selectSingleNode("/eLinkResult/LinkSet/DbFrom").getText();
    String idStr = document.selectSingleNode("/eLinkResult/LinkSet/IdList/Id").getText();
    Long id = Long.parseLong(idStr);
    List<Node> linkSetDbs = document.selectNodes("/eLinkResult/LinkSet/LinkSetDb");
    ArrayList<Relation> list = new ArrayList<Relation>();
    for (Node linkSetDb : linkSetDbs) {
        String toDb = linkSetDb.selectSingleNode("DbTo").getText();
        String linkName = linkSetDb.selectSingleNode("LinkName").getText();
        List<Node> ids = linkSetDb.selectNodes("Link/Id");
        list.ensureCapacity(list.size() + ids.size());
        for (Node idNode : ids) {
            long relatedId = Long.parseLong(idNode.getText());
            if (id == relatedId)
                continue;
            Relation relation = new Relation();
            relation.setRelationName(linkName);
            relation.setFromDb(fromDb);//from  ww  w.j  av  a 2s  .c  o  m
            relation.setFromId(id);
            relation.setToDb(toDb);
            relation.setToId(relatedId);
            list.add(relation);
        }
    }
    return list;
}

From source file:edu.unc.lib.dl.util.ContainerContentsHelper.java

/**
 * @param oldXML/* w  ww  .ja  v  a 2 s .c o  m*/
 * @param container
 * @param children
 * @return
 */
public static Document addChildContentListInCustomOrder(Document oldXML, PID container, List<PID> children,
        Collection<PID> reorderedPids) {
    log.debug("HERE incoming children:");
    for (int i = 0; i < children.size(); i++) {
        log.debug(i + " => " + children.get(i));
    }

    // first build a list of existing pid order in the container
    Element parentDiv = oldXML.getRootElement().getChild("div", JDOMNamespaceUtil.METS_NS);
    List<Element> childDivs = parentDiv.getChildren();
    int maxExistingOrder = 5;
    if (childDivs.size() > 0) {
        maxExistingOrder = Integer.parseInt(childDivs.get(childDivs.size() - 1).getAttributeValue("ORDER"));
    }
    ArrayList<PID> order = new ArrayList<PID>(maxExistingOrder);
    try {
        for (Element child : childDivs) {
            int ord = Integer.parseInt(child.getAttributeValue("ORDER"));
            PID pid = new PID(child.getAttributeValue("ID"));
            if (ord >= order.size()) {
                while (ord > order.size()) { // insert nulls
                    order.add(null);
                }
                order.add(pid);
            } else {
                order.add(ord, pid);
            }
        }
    } catch (NullPointerException e) {
        throw new IllegalRepositoryStateException("Invalid container contents XML (MD_CONTENTS) on: ", e);
    }

    log.debug("HERE order before merge:");
    for (int i = 0; i < order.size(); i++) {
        log.debug(i + " => " + order.get(i));
    }

    PID[] originalOrder = order.toArray(new PID[0]);

    // clear out the current children
    parentDiv.removeContent();

    int maxIncomingOrder = 0;
    if (children.size() > 0) {
        maxIncomingOrder = children.size() - 1;
    }
    int capacityEstimate = Math.max(maxIncomingOrder, maxExistingOrder) + 10;
    order.ensureCapacity(capacityEstimate);

    for (ListIterator<PID> foo = children.listIterator(); foo.hasNext();) {
        int ord = foo.nextIndex();
        PID child = foo.next();
        if (ord >= order.size()) {
            while (ord > order.size()) { // insert nulls
                order.add(null);
            }
            order.add(child);
        } else {
            order.add(ord, child);
        }
    }

    log.debug("HERE order after merge:");
    for (int i = 0; i < order.size(); i++) {
        log.debug(i + " => " + order.get(i));
    }

    for (int i = 0; i < originalOrder.length; i++) {
        PID orig = originalOrder[i];
        if (orig != null) {
            if (!orig.equals(order.get(i))) {
                reorderedPids.add(orig);
            }
        }
    }

    for (ListIterator<PID> li = order.listIterator(); li.hasNext();) {
        int ord = li.nextIndex();
        PID pid = li.next();
        if (pid != null) {
            Element el = new Element("div", parentDiv.getNamespace()).setAttribute("ID", pid.getPid())
                    .setAttribute("ORDER", String.valueOf(ord));
            parentDiv.addContent(el);
        }
    }

    return oldXML;
}

From source file:org.kuali.ole.fp.document.web.struts.VoucherAction.java

/**
 * This method builds the corresponding list of voucher acounting line helper objects so that a user can differentiate between
 * credit and debit fields. It does this by iterating over each source accounting line (what the voucher uses) looking at the
 * debit/credit code and then populateingLineHelpers a corresponding helper form instance with the amount in the appropriate
 * amount field - credit or debit./*from w  ww . ja va 2  s . c  om*/
 * 
 * @param voucherForm
 */
protected void populateAllVoucherAccountingLineHelpers(VoucherForm voucherForm) {
    // make sure the journal voucher accounting line helper form list is populated properly
    ArrayList voucherLineHelpers = (ArrayList) voucherForm.getVoucherLineHelpers();

    // make sure the helper list is the right size
    VoucherDocument vDoc = (VoucherDocument) voucherForm.getTransactionalDocument();
    int size = vDoc.getSourceAccountingLines().size();
    voucherLineHelpers.ensureCapacity(size);

    // iterate through each source accounting line and initialize the helper form lines appropriately
    for (int i = 0; i < size; i++) {
        // get the bo's accounting line at the right index
        SourceAccountingLine sourceAccountingLine = vDoc.getSourceAccountingLine(i);

        // instantiate a new helper form to use for populating the helper form list
        VoucherAccountingLineHelper avAcctLineHelperForm = voucherForm.getVoucherLineHelper(i);

        // figure whether we need to set the credit amount or the debit amount
        if (StringUtils.isNotBlank(sourceAccountingLine.getDebitCreditCode())) {
            if (sourceAccountingLine.getDebitCreditCode().equals(OLEConstants.GL_DEBIT_CODE)) {
                avAcctLineHelperForm.setDebit(sourceAccountingLine.getAmount());
                avAcctLineHelperForm.setCredit(KualiDecimal.ZERO);
            } else if (sourceAccountingLine.getDebitCreditCode().equals(OLEConstants.GL_CREDIT_CODE)) {
                avAcctLineHelperForm.setCredit(sourceAccountingLine.getAmount());
                avAcctLineHelperForm.setDebit(KualiDecimal.ZERO);
            }
        }
    }
}

From source file:org.kuali.kfs.fp.document.web.struts.VoucherAction.java

/**
 * This method builds the corresponding list of voucher acounting line helper objects so that a user can differentiate between
 * credit and debit fields. It does this by iterating over each source accounting line (what the voucher uses) looking at the
 * debit/credit code and then populateingLineHelpers a corresponding helper form instance with the amount in the appropriate
 * amount field - credit or debit./*from   www . jav  a2  s  .  c o m*/
 * 
 * @param voucherForm
 */
protected void populateAllVoucherAccountingLineHelpers(VoucherForm voucherForm) {
    // make sure the journal voucher accounting line helper form list is populated properly
    ArrayList voucherLineHelpers = (ArrayList) voucherForm.getVoucherLineHelpers();

    // make sure the helper list is the right size
    VoucherDocument vDoc = (VoucherDocument) voucherForm.getTransactionalDocument();
    int size = vDoc.getSourceAccountingLines().size();
    voucherLineHelpers.ensureCapacity(size);

    // iterate through each source accounting line and initialize the helper form lines appropriately
    for (int i = 0; i < size; i++) {
        // get the bo's accounting line at the right index
        SourceAccountingLine sourceAccountingLine = vDoc.getSourceAccountingLine(i);

        // instantiate a new helper form to use for populating the helper form list
        VoucherAccountingLineHelper avAcctLineHelperForm = voucherForm.getVoucherLineHelper(i);

        // figure whether we need to set the credit amount or the debit amount
        if (StringUtils.isNotBlank(sourceAccountingLine.getDebitCreditCode())) {
            if (sourceAccountingLine.getDebitCreditCode().equals(KFSConstants.GL_DEBIT_CODE)) {
                avAcctLineHelperForm.setDebit(sourceAccountingLine.getAmount());
                avAcctLineHelperForm.setCredit(KualiDecimal.ZERO);
            } else if (sourceAccountingLine.getDebitCreditCode().equals(KFSConstants.GL_CREDIT_CODE)) {
                avAcctLineHelperForm.setCredit(sourceAccountingLine.getAmount());
                avAcctLineHelperForm.setDebit(KualiDecimal.ZERO);
            }
        }
    }
}

From source file:com.android.settings.aoip.WidgetsConfiguration.java

private ArrayList<NavBarWidget> inflateWidgets() {
    ArrayList<NavBarWidget> widgets = new ArrayList<NavBarWidget>();
    String settingWidgets = Settings.System.getString(mContext.getContentResolver(),
            Settings.System.NAVIGATION_BAR_WIDGETS);
    if (settingWidgets != null && settingWidgets.length() > 0) {
        String[] split = settingWidgets.split("\\|");
        widgets.ensureCapacity(split.length + 1);
        for (int i = 0; i < split.length; i++) {
            int appWidgetId = Integer.parseInt(split[i]);
            widgets.add(new NavBarWidget(appWidgetId));
        }/*from  ww w . jav a2  s. com*/
    }
    widgets.add(new NavBarWidget(-1)); // add +1 button!
    return widgets;
}

From source file:org.kuali.ole.fp.document.web.struts.JournalVoucherAction.java

/**
 * This method will clear out the source line values that aren't needed for the "Single Amount" mode.
 * //from ww w  . jav  a 2 s .com
 * @param journalVoucherForm
 */
protected void switchFromSingleAmountModeToCreditDebitMode(JournalVoucherForm journalVoucherForm) {
    // going from single amount to credit/debit view so we want to blank out the amount and the extra "reference" fields
    // that the single amount view uses
    JournalVoucherDocument jvDoc = (JournalVoucherDocument) journalVoucherForm.getTransactionalDocument();
    ArrayList sourceLines = (ArrayList) jvDoc.getSourceAccountingLines();
    ArrayList helperLines = (ArrayList) journalVoucherForm.getVoucherLineHelpers();
    helperLines.clear(); // reset so we can add in fresh empty ones

    // make sure that there is enough space in the list
    helperLines.ensureCapacity(sourceLines.size());

    for (int i = 0; i < sourceLines.size(); i++) {
        VoucherSourceAccountingLine sourceLine = (VoucherSourceAccountingLine) sourceLines.get(i);
        sourceLine.setAmount(KualiDecimal.ZERO);
        sourceLine.setDebitCreditCode(OLEConstants.GL_DEBIT_CODE); // default to debit

        helperLines.add(new VoucherAccountingLineHelperBase()); // populate with a fresh new empty object
    }
}

From source file:org.kuali.kfs.fp.document.web.struts.JournalVoucherAction.java

/**
 * This method will clear out the source line values that aren't needed for the "Single Amount" mode.
 * /* w  w  w. j av  a  2 s. com*/
 * @param journalVoucherForm
 */
protected void switchFromSingleAmountModeToCreditDebitMode(JournalVoucherForm journalVoucherForm) {
    // going from single amount to credit/debit view so we want to blank out the amount and the extra "reference" fields
    // that the single amount view uses
    JournalVoucherDocument jvDoc = (JournalVoucherDocument) journalVoucherForm.getTransactionalDocument();
    ArrayList sourceLines = (ArrayList) jvDoc.getSourceAccountingLines();
    ArrayList helperLines = (ArrayList) journalVoucherForm.getVoucherLineHelpers();
    helperLines.clear(); // reset so we can add in fresh empty ones

    // make sure that there is enough space in the list
    helperLines.ensureCapacity(sourceLines.size());

    for (int i = 0; i < sourceLines.size(); i++) {
        VoucherSourceAccountingLine sourceLine = (VoucherSourceAccountingLine) sourceLines.get(i);
        sourceLine.setAmount(KualiDecimal.ZERO);
        sourceLine.setDebitCreditCode(KFSConstants.GL_DEBIT_CODE); // default to debit

        helperLines.add(new VoucherAccountingLineHelperBase()); // populate with a fresh new empty object
    }
}

From source file:io.agi.framework.persistence.DataJsonSerializer.java

public static String FloatArrayToString(FloatArray fa, String encoding) {
    String s1 = "{ \"encoding\":\"" + encoding + "\",\"length\":";
    String s2 = ",\"elements\":["; // put elements last
    String s3 = "]}";

    String length = String.valueOf(fa._values.length);
    ArrayList<String> chunks = new ArrayList<String>();
    ArrayList<String> values = new ArrayList<String>();
    int chunkSize = 100;

    if ((encoding != null) && (encoding.equals(ENCODING_SPARSE_BINARY))) {
        for (int i = 0; i < fa._values.length; ++i) {
            float value = fa._values[i];
            if (value == 0.f) {
                continue; // only add the nonzero value indices.
            }/* ww w  .  j av  a  2 s  . co  m*/

            String s = String.valueOf(i); // Important! Serializing this as integer.
            values.add(s);
            if (values.size() >= chunkSize) {
                String chunk = StringUtils.join(values, ",");
                chunks.add(chunk);
                values.clear();
            }
        }
    } else if ((encoding != null) && (encoding.equals(ENCODING_SPARSE_REAL))) {
        for (int i = 0; i < fa._values.length; ++i) {
            float value = fa._values[i];
            if (value == 0.f) {
                continue; // only add the nonzero value indices.
            }

            String s = String.valueOf(i) + "," + String.valueOf(value); // index,value
            values.add(s);
            if (values.size() >= chunkSize) {
                String chunk = StringUtils.join(values, ",");
                chunks.add(chunk);
                values.clear();
            }
        }
        //System.err.println( " Sparse real encoding: Original size: " + fa._values.length + " encoded size: " + values.size() );
    } else {
        values.ensureCapacity(fa._values.length);
        for (int i = 0; i < fa._values.length; ++i) {
            float value = fa._values[i];
            String s = String.valueOf(value);
            values.add(s);
            if (values.size() >= chunkSize) {
                String chunk = StringUtils.join(values, ",");
                chunks.add(chunk);
                values.clear();
            }
        }
    }

    // clear last values into chunks
    if (values.size() > 0) {
        String chunk = StringUtils.join(values, ",");
        chunks.add(chunk);
        values.clear();
    }

    String elements = StringUtils.join(chunks, ",");
    String result = s1 + length + s2 + elements + s3;
    return result;
}

From source file:org.opennms.ng.dao.support.InterfaceSnmpResourceType.java

private List<String> getQueryableInterfacesForDomain(String domain) {
    if (domain == null) {
        throw new IllegalArgumentException("Cannot take null parameters.");
    }/*w ww  .ja  v a  2s. co m*/

    ArrayList<String> intfs = new ArrayList<String>();
    File snmp = new File(m_resourceDao.getRrdDirectory(), DefaultResourceDao.SNMP_DIRECTORY);
    File domainDir = new File(snmp, domain);

    if (!domainDir.exists() || !domainDir.isDirectory()) {
        throw new IllegalArgumentException("No such directory: " + domainDir);
    }

    File[] intfDirs = domainDir.listFiles(RrdFileConstants.DOMAIN_INTERFACE_DIRECTORY_FILTER);

    if (intfDirs != null && intfDirs.length > 0) {
        intfs.ensureCapacity(intfDirs.length);
        for (int i = 0; i < intfDirs.length; i++) {
            intfs.add(intfDirs[i].getName());
        }
    }

    return intfs;
}

From source file:eu.stratosphere.hadoopcompatibility.mapred.HadoopInputFormat.java

private FileBaseStatistics getFileStats(FileBaseStatistics cachedStats,
        org.apache.hadoop.fs.Path[] hadoopFilePaths, ArrayList<FileStatus> files) throws IOException {

    long latestModTime = 0L;

    // get the file info and check whether the cached statistics are still valid.
    for (org.apache.hadoop.fs.Path hadoopPath : hadoopFilePaths) {

        final Path filePath = new Path(hadoopPath.toUri());
        final FileSystem fs = FileSystem.get(filePath.toUri());

        final FileStatus file = fs.getFileStatus(filePath);
        latestModTime = Math.max(latestModTime, file.getModificationTime());

        // enumerate all files and check their modification time stamp.
        if (file.isDir()) {
            FileStatus[] fss = fs.listStatus(filePath);
            files.ensureCapacity(files.size() + fss.length);

            for (FileStatus s : fss) {
                if (!s.isDir()) {
                    files.add(s);//from  w  w  w.  j a  v  a  2s .  c  o m
                    latestModTime = Math.max(s.getModificationTime(), latestModTime);
                }
            }
        } else {
            files.add(file);
        }
    }

    // check whether the cached statistics are still valid, if we have any
    if (cachedStats != null && latestModTime <= cachedStats.getLastModificationTime()) {
        return cachedStats;
    }

    // calculate the whole length
    long len = 0;
    for (FileStatus s : files) {
        len += s.getLen();
    }

    // sanity check
    if (len <= 0) {
        len = BaseStatistics.SIZE_UNKNOWN;
    }

    return new FileBaseStatistics(latestModTime, len, BaseStatistics.AVG_RECORD_BYTES_UNKNOWN);
}