java.util.ArrayList.trimToSize()方法的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(9.2k)|赞(0)|评价(0)|浏览(227)

本文整理了Java中java.util.ArrayList.trimToSize()方法的一些代码示例,展示了ArrayList.trimToSize()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ArrayList.trimToSize()方法的具体详情如下:
包路径:java.util.ArrayList
类名称:ArrayList
方法名:trimToSize

ArrayList.trimToSize介绍

[英]Sets the capacity of this ArrayList to be the same as the current size.
[中]将此ArrayList的容量设置为与当前大小相同。

代码示例

代码示例来源:origin: org.freemarker/freemarker

private static final List removeDuplicates(List list) {
  int s = list.size();
  ArrayList ulist = new ArrayList(s);
  Set set = new HashSet(s * 4 / 3, .75f);
  Iterator it = list.iterator();
  while (it.hasNext()) {
    Object o = it.next();
    if (set.add(o))
      ulist.add(o);
  }
  ulist.trimToSize();
  return ulist;
}

代码示例来源:origin: konsoletyper/teavm

List<ConsumerWithNode> getConsumers() {
  if (consumers == null) {
    consumers = new ArrayList<>();
    for (DependencyNode node : domain) {
      if (node.followers != null) {
        consumers.add(new ConsumerWithNode(node.followers.toArray(new DependencyConsumer[0]), node));
      }
    }
    consumers.trimToSize();
  }
  return consumers;
}

代码示例来源:origin: wildfly/wildfly

static <T> List<T> loadServices(Class<T> type, ClassLoader classLoader) {
  return doPrivileged((PrivilegedAction<List<T>>) () -> {
    ArrayList<T> list = new ArrayList<>();
    Iterator<T> iterator = ServiceLoader.load(type, classLoader).iterator();
    for (;;) try {
      if (! iterator.hasNext()) break;
      final T contextFactory = iterator.next();
      list.add(contextFactory);
    } catch (ServiceConfigurationError error) {
      Messages.log.serviceConfigFailed(error);
    }
    list.trimToSize();
    return list;
  });
}

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Returns text as a List of tokens.
 *
 * @return A list of all tokens remaining in the underlying Reader
 */
@Override
public List<T> tokenize() {
 ArrayList<T> result = new ArrayList<>(DEFAULT_TOKENIZE_LIST_SIZE);
 while (hasNext()) {
  result.add(next());
 }
 // log.info("tokenize() produced " + result);
 // if it was tiny, reallocate small
 if (result.size() <= DEFAULT_TOKENIZE_LIST_SIZE / 4) {
  result.trimToSize();
 }
 return result;
}

代码示例来源:origin: wildfly/wildfly

/**
 * Construct a new instance.  The given class loader is scanned for transaction providers.
 *
 * @param classLoader the class loader to scan for transaction providers ({@code null} indicates the application or bootstrap class loader)
 */
public RemoteTransactionContext(final ClassLoader classLoader) {
  this(doPrivileged((PrivilegedAction<List<RemoteTransactionProvider>>) () -> {
    final ServiceLoader<RemoteTransactionProvider> loader = ServiceLoader.load(RemoteTransactionProvider.class, classLoader);
    final ArrayList<RemoteTransactionProvider> providers = new ArrayList<RemoteTransactionProvider>();
    final Iterator<RemoteTransactionProvider> iterator = loader.iterator();
    for (;;) try {
      if (! iterator.hasNext()) break;
      providers.add(iterator.next());
    } catch (ServiceConfigurationError e) {
      Log.log.serviceConfigurationFailed(e);
    }
    providers.trimToSize();
    return providers;
  }), false);
}

代码示例来源:origin: hibernate/hibernate-orm

private static List<StandardServiceInitiator> buildStandardServiceInitiatorList() {
  final ArrayList<StandardServiceInitiator> serviceInitiators = new ArrayList<StandardServiceInitiator>();
  serviceInitiators.add( CfgXmlAccessServiceInitiator.INSTANCE );
  serviceInitiators.add( ConfigurationServiceInitiator.INSTANCE );
  serviceInitiators.add( PropertyAccessStrategyResolverInitiator.INSTANCE );
  serviceInitiators.add( ImportSqlCommandExtractorInitiator.INSTANCE );
  serviceInitiators.add( EntityCopyObserverFactoryInitiator.INSTANCE );
  serviceInitiators.trimToSize();

代码示例来源:origin: nutzam/nutz

List<LinkField> getList(String regex) {
  ArrayList<LinkField> list;
  if (Strings.isBlank(regex)) {
    list = lnks;
  } else {
    list = cache.get(regex);
    if (null == list) {
      synchronized (cache) {
        list = cache.get(regex);
        if (null == list) {
          list = new ArrayList<LinkField>(lnks.size());
          for (LinkField lnk : lnks)
            if (Pattern.matches(regex, lnk.getName()))
              list.add(lnk);
          list.trimToSize();
          cache.put(regex, list);
        }
      }
    }
  }
  return list;
}

代码示例来源:origin: org.freemarker/freemarker

/**
 * Constructs a simple sequence from the passed collection model, which shouldn't be added to later. The internal
 * list will be build immediately (not lazily). The resulting sequence shouldn't be extended with
 * {@link #add(Object)}, because the appropriate {@link ObjectWrapper} won't be available; use
 * {@link #SimpleSequence(Collection, ObjectWrapper)} instead, if you need that.
 */
public SimpleSequence(TemplateCollectionModel tcm) throws TemplateModelException {
  ArrayList alist = new ArrayList();
  for (TemplateModelIterator it = tcm.iterator(); it.hasNext(); ) {
    alist.add(it.next());
  }
  alist.trimToSize();
  list = alist;
}

代码示例来源:origin: Sable/soot

@Override
 public Collection<Unit> load(SootMethod m) throws Exception {
  ArrayList<Unit> res = new ArrayList<Unit>();
  // only retain callers that are explicit call sites or
  // Thread.start()
  Iterator<Edge> edgeIter = new EdgeFilter().wrap(cg.edgesInto(m));
  while (edgeIter.hasNext()) {
   Edge edge = edgeIter.next();
   res.add(edge.srcUnit());
  }
  res.trimToSize();
  return res;
 }
};

代码示例来源:origin: wildfly/wildfly

protected List<PoolConfiguration> getMatchingPoolConfigs(String poolName, ManagementRepository repository) {
  ArrayList<PoolConfiguration> result = new ArrayList<PoolConfiguration>(repository.getDataSources().size());
  if (repository.getDataSources() != null) {
    for (DataSource ds : repository.getDataSources()) {
      if (poolName.equalsIgnoreCase(ds.getPool().getName())) {
        result.add(ds.getPoolConfiguration());
      }
    }
  }
  result.trimToSize();
  return result;
}

代码示例来源:origin: org.apache.commons/commons-collections4

final O item = iterator.next();
  if (lastItem == null || !lastItem.equals(item)) {
    mergedList.add(item);
mergedList.trimToSize();
return mergedList;

代码示例来源:origin: wildfly/wildfly

public List<Pool> match(String jndiName, ManagementRepository repository) {
    ArrayList<org.jboss.jca.core.api.connectionmanager.pool.Pool> result = new ArrayList<Pool>(repository
        .getDataSources().size());
    if (repository.getDataSources() != null) {
      for (DataSource ds : repository.getDataSources()) {
        if (jndiName.equalsIgnoreCase(ds.getJndiName()) && ds.getPool() != null) {
          result.add(ds.getPool());
        }
      }
    }
    result.trimToSize();
    return result;
  }
}

代码示例来源:origin: Sable/soot

successors.add(nextUnit);
  successors.add(target);
successors.trimToSize();
unitToSuccs.put(currentUnit, successors);

代码示例来源:origin: Sable/soot

@Override
 public Collection<SootMethod> load(Unit u) throws Exception {
  ArrayList<SootMethod> res = null;
  // only retain callers that are explicit call sites or
  // Thread.start()
  Iterator<Edge> edgeIter = new EdgeFilter().wrap(cg.edgesOutOf(u));
  while (edgeIter.hasNext()) {
   Edge edge = edgeIter.next();
   SootMethod m = edge.getTgt().method();
   if (includePhantomCallees || m.hasActiveBody()) {
    if (res == null) {
     res = new ArrayList<SootMethod>();
    }
    res.add(m);
   } else if (IDESolver.DEBUG) {
    logger.error(String.format("Method %s is referenced but has no body!", m.getSignature(), new Exception()));
   }
  }
  if (res != null) {
   res.trimToSize();
   return res;
  } else {
   return Collections.emptySet();
  }
 }
};

代码示例来源:origin: wildfly/wildfly

protected List<PoolConfiguration> getMatchingPoolConfigs(String poolName, ManagementRepository repository) {
  ArrayList<PoolConfiguration> result = new ArrayList<PoolConfiguration>(repository.getConnectors().size());
  if (repository.getConnectors() != null) {
    for (Connector conn : repository.getConnectors()) {
      if (conn.getConnectionFactories() == null || conn.getConnectionFactories().get(0) == null
          || conn.getConnectionFactories().get(0).getPool() == null)
        continue;
      ConnectionFactory connectionFactory = conn.getConnectionFactories().get(0);
      if (poolName.equals(connectionFactory.getPool().getName())) {
        PoolConfiguration pc = conn.getConnectionFactories().get(0).getPoolConfiguration();
        result.add(pc);
      }
    }
  }
  result.trimToSize();
  return result;
}

代码示例来源:origin: opentripplanner/OpenTripPlanner

private List<ShapePoint> getUniqueShapePointsForShapeId(FeedScopedId shapeId) {
  List<ShapePoint> points = transitService.getShapePointsForShapeId(shapeId);
  ArrayList<ShapePoint> filtered = new ArrayList<ShapePoint>(points.size());
  ShapePoint last = null;
  for (ShapePoint sp : points) {
    if (last == null || last.getSequence() != sp.getSequence()) {
      if (last != null && 
        last.getLat() == sp.getLat() && 
        last.getLon() == sp.getLon()) {
        LOG.trace("pair of identical shape points (skipping): {} {}", last, sp);
      } else {
        filtered.add(sp);
      }
    }
    last = sp;
  }
  if (filtered.size() != points.size()) {
    filtered.trimToSize();
    return filtered;
  } else {
    return points;
  }
}

代码示例来源:origin: apache/ignite

keyCols.add(keyCol);
  else {
    for (String propName : type.fields().keySet()) {
        Column col = tbl.getColumn(propName);
        keyCols.add(tbl.indexColumn(col.getColumnId(), SortOrder.ASCENDING));
      keyCols.add(keyCol);
  keyCols.add(affCol);
else
  keyCols.trimToSize();

代码示例来源:origin: qiujuer/Genius-Android

break;
  } else {
    routes.add(container.toString());
    prevIP = container.mIP;
routes.trimToSize();
mRoutes = routes;

代码示例来源:origin: spring-projects/spring-security

attrs.add(pre);
  attrs.add(post);
attrs.trimToSize();

代码示例来源:origin: robovm/robovm

private void decodeValueCollection(ASN1ValueCollection collection) throws IOException {
  int begOffset = offset;
  int endOffset = begOffset + length;
  ASN1Type type = collection.type;
  if (isVerify) {
    while (endOffset > offset) {
      next();
      type.decode(this);
    }
  } else {
    int seqTagOffset = tagOffset; //store tag offset
    ArrayList<Object> values = new ArrayList<Object>();
    while (endOffset > offset) {
      next();
      values.add(type.decode(this));
    }
    values.trimToSize();
    content = values;
    tagOffset = seqTagOffset; //retrieve tag offset
  }
  if (offset != endOffset) {
    throw new ASN1Exception("Wrong encoding at [" + begOffset + "]. Content's length and encoded length are not the same");
  }
}

相关文章