Java Code Examples for java.util.ArrayList#trimToSize()

The following examples show how to use java.util.ArrayList#trimToSize() . 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: MSKStarDoer.java    From OSPREY3 with GNU General Public License v2.0 6 votes vote down vote up
private void listAllSeqsHelper(ArrayList<ArrayList<String>> subStateAATypeOptions, 
		ArrayList<ArrayList<String>> stateOutput, String[] wt, String[] buf, int depth, int dist){
	//List all sequences for the subset of mutable positions with max distance
	//from wt starting at depth=0 and going to the last mutable position
	if(depth==numMutRes){
		//String[] seq = new String[numTreeLevels];
		//System.arraycopy(buf, 0, seq, 0, numTreeLevels);
		ArrayList<String> seq = new ArrayList<String>(Arrays.asList(buf));
		seq.trimToSize();
		stateOutput.add(seq);
		return;
	}

	for(int aaIndex=0;aaIndex<subStateAATypeOptions.get(depth).size();++aaIndex){
		buf[depth]=subStateAATypeOptions.get(depth).get(aaIndex);
		int nDist=buf[depth].equalsIgnoreCase(wt[depth]) ? dist : dist+1;
		if(nDist>numMaxMut) continue;
		listAllSeqsHelper(subStateAATypeOptions, stateOutput, wt, buf, depth+1, nDist);
	}
}
 
Example 2
Source File: TypeLibrary.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static Type createAnnotationType(Class<? extends Annotation> a) {
    if (shouldPersist(a)) {
        Type type = defineType(a, Type.SUPER_TYPE_ANNOTATION, false);
        if (type != null) {
            SecuritySupport.makeVisibleToJFR(a);
            for (Method method : a.getDeclaredMethods()) {
                type.add(PrivateAccess.getInstance().newValueDescriptor(method.getReturnType(), method.getName()));
            }
            ArrayList<AnnotationElement> aes = new ArrayList<>();
            for (Annotation annotation : resolveRepeatedAnnotations(a.getAnnotations())) {
                AnnotationElement ae = createAnnotation(annotation);
                if (ae != null) {
                    aes.add(ae);
                }
            }
            aes.trimToSize();
            type.setAnnotations(aes);
        }
        return getType(a);
    }
    return null;
}
 
Example 3
Source File: JSIndexQueryHelper.java    From APICloud-Studio with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets all the functions and properties for the given types.
 * 
 * @param typeNames
 * @return
 */
public Collection<PropertyElement> getTypeMembers(List<String> typeNames)
{
	if (CollectionsUtil.isEmpty(typeNames))
	{
		return Collections.emptyList();
	}
	ArrayList<PropertyElement> properties = new ArrayList<PropertyElement>();
	// FIXME Can we search both functions and properties at the same time?
	// FIXME What about "sub-types" that aren't hung explicitly off owning type? i.e. "Global.console"
	for (Index index : indices)
	{
		properties.addAll(_reader.getFunctions(index, typeNames));
		properties.addAll(_reader.getProperties(index, typeNames));
	}
	properties.trimToSize();
	return properties;
}
 
Example 4
Source File: Globals.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Finds all PObjects that match the passed in type.  All the types listed
 * in aType must match for the object to be returned.
 * @param aPObjectList List of PObjects to search
 * @param aType A "." separated list of TYPEs to match
 * @return List of PObjects matching all TYPEs
 */
public static <T extends CDOMObject> List<T> getPObjectsOfType(final Collection<T> aPObjectList, final String aType)
{
	final ArrayList<T> ret = new ArrayList<>(aPObjectList.size());

	final List<String> typeList = new ArrayList<>();
	final StringTokenizer tok = new StringTokenizer(aType, ".");
	while (tok.hasMoreTokens())
	{
		typeList.add(tok.nextToken());
	}

	for (final T anObject : aPObjectList)
	{
		if (isMatch(typeList, anObject))
		{
			ret.add(anObject);
		}
	}
	ret.trimToSize();
	return ret;
}
 
Example 5
Source File: MasterHooks.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Triggers all given master hooks and returns state objects for each hook that
 * produced a state.
 *
 * @param hooks The hooks to trigger
 * @param checkpointId The checkpoint ID of the triggering checkpoint
 * @param timestamp The (informational) timestamp for the triggering checkpoint
 * @param executor An executor that can be used for asynchronous I/O calls
 * @param timeout The maximum time that a hook may take to complete
 *
 * @return A list containing all states produced by the hooks
 *
 * @throws FlinkException Thrown, if the hooks throw an exception, or the state+
 *                        deserialization fails.
 */
public static List<MasterState> triggerMasterHooks(
		Collection<MasterTriggerRestoreHook<?>> hooks,
		long checkpointId,
		long timestamp,
		Executor executor,
		Time timeout) throws FlinkException {

	final ArrayList<MasterState> states = new ArrayList<>(hooks.size());

	for (MasterTriggerRestoreHook<?> hook : hooks) {
		MasterState state = triggerHook(hook, checkpointId, timestamp, executor, timeout);
		if (state != null) {
			states.add(state);
		}
	}

	states.trimToSize();
	return states;
}
 
Example 6
Source File: ModelEntity.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Modifies the given collections to be atomic and creates a new read-only instance from them.
 * <p>
 * WARN: Do not pass the collections from existing instance to this without making copy first.
 */
public static Fields optimizeAndCreate(ArrayList<ModelField> fieldsList, Map<String, ModelField> fieldsMap, ArrayList<String> pkFieldNames,
        ArrayList<ModelField> pks, ArrayList<ModelField> nopks) {
    fieldsList.trimToSize();
    pkFieldNames.trimToSize();
    pks.trimToSize();
    nopks.trimToSize();
    return new Fields(fieldsList, fieldsMap, pkFieldNames, pks, nopks);
}
 
Example 7
Source File: DiskSelectionFilter.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses config/diskselection.conf and load the filters.<br>
 * Filters classes MUST follow this naming scheme:<br>
 * First letter uppercase, and add the "Filter" in the end.<br>
 * For example: 'minfreespace' filter, class = MinfreespaceFilter.class<br>
 */
private void loadFilters(Properties p) {
    ArrayList<DiskFilter> filters = new ArrayList<>();
    int i = 1;

    logger.info("Loading DiskSelection filters...");

    for (; ; i++) {
        String filterName = p.getProperty(i + ".filter");

        if (filterName == null) {
            break;
        }

        if (!_filtersMap.containsKey(filterName)) {
            // if we can't find one filter that will be enought to brake the whole chain.
            throw new RuntimeException(filterName + " wasn't loaded.");
        }

        try {
            Class<? extends DiskFilter> clazz = _filtersMap.get(filterName);
            DiskFilter filter = clazz.getConstructor(SIG).newInstance(this, p, i);
            filters.add(filter);
        } catch (Exception e) {
            throw new RuntimeException(i + ".filter = " + filterName, e);
        }
    }

    filters.trimToSize();
    _filters = filters;
}
 
Example 8
Source File: CallClassMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public CallClassMethod(Element element, SimpleMethod simpleMethod) throws MiniLangException {
    super(element, simpleMethod);
    if (MiniLangValidate.validationOn()) {
        if (MiniLangValidate.deprecatedCommonOn()) { // SCIPIO
            MiniLangValidate.handleError("<call-class-method> element is deprecated (use <script>)", simpleMethod, element);
        }
        MiniLangValidate.attributeNames(simpleMethod, element, "class-name", "method-name", "ret-field");
        MiniLangValidate.constantAttributes(simpleMethod, element, "class-name", "method-name");
        MiniLangValidate.requiredAttributes(simpleMethod, element, "class-name", "method-name");
        MiniLangValidate.childElements(simpleMethod, element, "string", "field");
    }
    this.className = element.getAttribute("class-name");
    Class<?> methodClass = null;
    try {
        methodClass = ObjectType.loadClass(this.className);
    } catch (ClassNotFoundException e) {
        MiniLangValidate.handleError("Class not found with name " + this.className, simpleMethod, element);
    }
    this.methodClass = methodClass;
    this.methodName = element.getAttribute("method-name");
    this.retFieldFma = FlexibleMapAccessor.getInstance(element.getAttribute("ret-field"));
    List<? extends Element> parameterElements = UtilXml.childElementList(element);
    if (parameterElements.size() > 0) {
        ArrayList<MethodObject<?>> parameterList = new ArrayList<MethodObject<?>>(parameterElements.size());
        for (Element parameterElement : parameterElements) {
            if ("string".equals(parameterElement.getNodeName())) {
                parameterList.add(new StringObject(parameterElement, simpleMethod));
            } else if ("field".equals(parameterElement.getNodeName())) {
                parameterList.add(new FieldObject<Object>(parameterElement, simpleMethod));
            }
        }
        parameterList.trimToSize();
        this.parameters = Collections.unmodifiableList(parameterList);
    } else {
        this.parameters = null;
    }
}
 
Example 9
Source File: UnpickleStack.java    From big-c with Apache License 2.0 5 votes vote down vote up
public ArrayList<Object> pop_all_since_marker() {
	ArrayList<Object> result = new ArrayList<Object>();
	Object o = pop();
	while (o != this.MARKER) {
		result.add(o);
		o = pop();
	}
	result.trimToSize();
	Collections.reverse(result);
	return result;
}
 
Example 10
Source File: Compiler.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static List<CompilationPhase> concatPhases(final CompilationPhases[] bases) {
    final ArrayList<CompilationPhase> l = new ArrayList<>();
    for(final CompilationPhases base: bases) {
        l.addAll(base.phases);
    }
    l.trimToSize();
    return l;
}
 
Example 11
Source File: Parser.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static <T> List<T> optimizeList(ArrayList<T> list) {
    switch(list.size()) {
        case 0: {
            return Collections.emptyList();
        }
        case 1: {
            return Collections.singletonList(list.get(0));
        }
        default: {
            list.trimToSize();
            return list;
        }
    }
}
 
Example 12
Source File: Parser.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static <T> List<T> optimizeList(final ArrayList<T> list) {
    switch(list.size()) {
        case 0: {
            return Collections.emptyList();
        }
        case 1: {
            return Collections.singletonList(list.get(0));
        }
        default: {
            list.trimToSize();
            return list;
        }
    }
}
 
Example 13
Source File: Parser.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Same as the other method of the same name - except that the end
 * token type expected is passed as argument to this method.
 *
 * FormalParameterList :
 *      Identifier
 *      FormalParameterList , Identifier
 *
 * See 13
 *
 * Parse function parameter list.
 * @return List of parameter nodes.
 */
private List<IdentNode> formalParameterList(final TokenType endType) {
    // Prepare to gather parameters.
    final ArrayList<IdentNode> parameters = new ArrayList<>();
    // Track commas.
    boolean first = true;

    while (type != endType) {
        // Comma prior to every argument except the first.
        if (!first) {
            expect(COMMARIGHT);
        } else {
            first = false;
        }

        // Get and add parameter.
        final IdentNode ident = getIdent();

        // ECMA 13.1 strict mode restrictions
        verifyStrictIdent(ident, "function parameter");

        parameters.add(ident);
    }

    parameters.trimToSize();
    return parameters;
}
 
Example 14
Source File: TraceHandler.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private Type createType(Attributes attributes, boolean eventType, long typeId, boolean contantPool) {
    String labelAttribute = ATTRIBUTE_LABEL;
    String id = attributes.getValue(ATTRIBUTE_ID);
    String path = attributes.getValue(ATTRIBUTE_PATH);
    String builtInType = attributes.getValue(ATTRIBUTE_BUILTIN_TYPE);
    String jvmType = attributes.getValue(ATTRIBUTE_JVM_TYPE);

    String typeName = makeTypeName(id, path);
    Type t;
    if (eventType) {
        t = new PlatformEventType(typeName, typeId, false, true);
    } else {
        t = new Type(typeName, null, typeId, contantPool);
    }
    typedef.put(id, typeName);
    if (contantPool) {
        labelAttribute = ATTRIBUTE_HR_NAME; // not "label" for some reason?
        if (builtInType != null) {
            typedef.put(builtInType, typeName);
        }
        if (jvmType != null) {
            typedef.put(jvmType, typeName);
        }
    }
    ArrayList<AnnotationElement> aes = new ArrayList<>();
    if (path != null) {
        aes.add(new AnnotationElement(Category.class, makeCategory(path)));
    }
    String label = attributes.getValue(labelAttribute);
    if (label != null) {
        aes.add(new AnnotationElement(Label.class, label));
    }
    String description = attributes.getValue(ATTRIBUTE_DESCRIPTION);
    if (description != null) {
        aes.add(new AnnotationElement(Description.class, description));
    }
    aes.trimToSize();
    t.setAnnotations(aes);
    return t;
}
 
Example 15
Source File: Package.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void trimToSize() {
    super.trimToSize();
    for (int isM = 0; isM <= 1; isM++) {
        ArrayList<? extends Member> members = (isM == 0) ? fields : methods;
        if (members == null)  continue;
        members.trimToSize();
        for (Member m : members) {
            m.trimToSize();
        }
    }
    if (innerClasses != null) {
        innerClasses.trimToSize();
    }
}
 
Example 16
Source File: Package.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void trimToSize() {
    super.trimToSize();
    for (int isM = 0; isM <= 1; isM++) {
        ArrayList<? extends Member> members = (isM == 0) ? fields : methods;
        if (members == null)  continue;
        members.trimToSize();
        for (Member m : members) {
            m.trimToSize();
        }
    }
    if (innerClasses != null) {
        innerClasses.trimToSize();
    }
}
 
Example 17
Source File: Compiler.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static <T> List<T> concat(final List<T> l1, final List<T> l2) {
    final ArrayList<T> l = new ArrayList<>(l1);
    l.addAll(l2);
    l.trimToSize();
    return l;
}
 
Example 18
Source File: RaParser.java    From ironjacamar with Eclipse Public License 1.0 4 votes vote down vote up
private Messageadapter parseMessageAdapter(XMLStreamReader reader) throws XMLStreamException, ParserException
{
   ArrayList<MessageListener> messagelistener = new ArrayList<MessageListener>();
   String id = reader.getAttributeValue(null, XML.ATTRIBUTE_ID);

   while (reader.hasNext())
   {
      switch (reader.nextTag())
      {
         case END_ELEMENT : {
            if (XML.ELEMENT_MESSAGEADAPTER.equals(reader.getLocalName()))
            {
               //trimming collections
               messagelistener.trimToSize();

               //building and returning object
               return new MessageAdapterImpl(messagelistener, id);
            }
            else
            {
               switch (reader.getLocalName())
               {
                  case XML.ELEMENT_MESSAGELISTENER :
                     break;
                  default :
                     throw new ParserException(bundle.unexpectedEndTag(reader.getLocalName()));
               }
            }
            break;
         }
         case START_ELEMENT : {
            switch (reader.getLocalName())
            {
               case XML.ELEMENT_MESSAGELISTENER : {
                  messagelistener.add(parseMessageListener(reader));
                  break;
               }
               default :
                  throw new ParserException(bundle.unexpectedElement(reader.getLocalName()));
            }
            break;
         }
      }
   }
   throw new ParserException(bundle.unexpectedEndOfDocument());
}
 
Example 19
Source File: CardinalityCompositeSpec.java    From jolt with Apache License 2.0 4 votes vote down vote up
public CardinalityCompositeSpec( String rawKey, Map<String, Object> spec ) {
    super( rawKey );

    Map<String, CardinalitySpec> literals = new HashMap<>();
    ArrayList<CardinalitySpec> computed = new ArrayList<>();

    specialChild = null;

    // self check
    if ( pathElement instanceof AtPathElement ) {
        throw new SpecException( "@ CardinalityTransform key, can not have children." );
    }

    List<CardinalitySpec> children = createChildren( spec );

    if ( children.isEmpty() ) {
        throw new SpecException( "Shift CardinalitySpec format error : CardinalitySpec line with empty {} as value is not valid." );
    }

    for ( CardinalitySpec child : children ) {
        literals.put( child.pathElement.getRawKey(), child );

        if ( child.pathElement instanceof LiteralPathElement ) {
            literals.put( child.pathElement.getRawKey(), child );
        }
        // special is it is "@"
        else if ( child.pathElement instanceof AtPathElement ) {
            if ( child instanceof CardinalityLeafSpec ) {
                specialChild = (CardinalityLeafSpec) child;
            } else {
                throw new SpecException( "@ CardinalityTransform key, can not have children." );
            }
        } else {   // star
            computed.add( child );
        }
    }

    // Only the computed children need to be sorted
    Collections.sort( computed, computedKeysComparator );

    computed.trimToSize();
    literalChildren = Collections.unmodifiableMap( literals );
    computedChildren = Collections.unmodifiableList( computed );
}
 
Example 20
Source File: CollectionUtil.java    From common-utils with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 创建<code>ArrayList</code>实例
 * 
 * @param iter 迭代器 @see Iterable
 * @return <code>ArrayList</code>实例
 */
public static <E> ArrayList<E> createArrayList(Iterable<? extends E> iter) {

    if (iter instanceof Collection<?>) {
        return new ArrayList<E>((Collection<? extends E>) iter);
    }

    ArrayList<E> list = new ArrayList<E>();

    iterableToCollection(iter, list);

    list.trimToSize();

    return list;
}