java.util.Collection.add()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(10.4k)|赞(0)|评价(0)|浏览(113)

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

Collection.add介绍

[英]Attempts to add object to the contents of this Collection (optional). After this method finishes successfully it is guaranteed that the object is contained in the collection. If the collection was modified it returns true, false if no changes were made. An implementation of Collection may narrow the set of accepted objects, but it has to specify this in the documentation. If the object to be added does not meet this restriction, then an IllegalArgumentException is thrown. If a collection does not yet contain an object that is to be added and adding the object fails, this method must throw an appropriate unchecked Exception. Returning false is not permitted in this case because it would violate the postcondition that the element will be part of the collection after this method finishes.
[中]尝试将对象添加到此集合的内容(可选)。此方法成功完成后,将保证对象包含在集合中。如果修改了集合,则返回true;如果未进行任何更改,则返回false。集合的实现可能会缩小可接受对象的范围,但它必须在文档中指定这一点。如果要添加的对象不满足此限制,则会引发IllegalArgumentException。如果集合尚未包含要添加的对象,并且添加该对象失败,则此方法必须引发相应的未检查异常。在这种情况下,不允许返回false,因为它将违反此方法完成后元素将成为集合一部分的后条件。

代码示例

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

@Nullable
private static Collection<String> appendSlashes(@Nullable Collection<String> prefixes) {
  if (CollectionUtils.isEmpty(prefixes)) {
    return prefixes;
  }
  Collection<String> result = new ArrayList<>(prefixes.size());
  for (String prefix : prefixes) {
    if (!prefix.endsWith("/")) {
      prefix = prefix + "/";
    }
    result.add(prefix);
  }
  return result;
}

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

@Override
protected Iterator<T> nextIteratorOrNull()
{
  if ( iterators.hasNext() )
  {
    currentIterator = iterators.next();
    seenIterators.add( currentIterator );
    return currentIterator;
  }
  return null;
}

代码示例来源:origin: apache/incubator-shardingsphere

@SuppressWarnings("unchecked")
private static <T> void registerServiceClass(final Class<T> service, final T instance) {
  Collection<Class<?>> serviceClasses = SERVICE_MAP.get(service);
  if (null == serviceClasses) {
    serviceClasses = new LinkedHashSet<>();
  }
  serviceClasses.add(instance.getClass());
  SERVICE_MAP.put(service, serviceClasses);
}

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

private void replaceConstraints(Collection constraints, TypeDecl before, TypeDecl after) {
 Collection newConstraints = new ArrayList();
 for(Iterator i2 = constraints.iterator(); i2.hasNext(); ) {
  TypeDecl U = (TypeDecl)i2.next();
  if(U == before) { //  TODO: fix parameterized type
   i2.remove();
   newConstraints.add(after);
  }
 }
 constraints.addAll(newConstraints);
}

代码示例来源:origin: google/guava

throw new NullPointerException("null key in entry: null=" + Iterables.toString(values));
Collection<V> valueCollection = builderMap.get(key);
if (valueCollection != null) {
 for (V value : values) {
  checkEntryNotNull(key, value);
  valueCollection.add(value);
if (!valuesItr.hasNext()) {
 return this;
while (valuesItr.hasNext()) {
 V value = valuesItr.next();
 checkEntryNotNull(key, value);
 valueCollection.add(value);
builderMap.put(key, valueCollection);
return this;

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

@Override
public void add(K key, V value) {
 Collection<V> deltaC = deltaMap.get(key);
 if (deltaC == null) {
  deltaC = cf.newCollection();
  Collection<V> originalC = originalMap.get(key);
  if (originalC != null) {
   deltaC.addAll(originalC);
  }
  deltaMap.put(key, deltaC);
 }
 deltaC.add(value);
}

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

@Override
public void invoke(Integer value) throws Exception {
  Collection<Integer> collection = collections.get(key);
  synchronized (collection) {
    collection.add(value);
  }
}

代码示例来源:origin: apache/incubator-shardingsphere

/**
 * Load proxy configuration.
 *
 * @return proxy configuration
 * @throws IOException IO exception
 */
public ShardingConfiguration load() throws IOException {
  Collection<String> schemaNames = new HashSet<>();
  YamlProxyServerConfiguration serverConfig = loadServerConfiguration(new File(ShardingConfigurationLoader.class.getResource(CONFIG_PATH + SERVER_CONFIG_FILE).getFile()));
  File configPath = new File(ShardingConfigurationLoader.class.getResource(CONFIG_PATH).getFile());
  Collection<YamlProxyRuleConfiguration> ruleConfigurations = new LinkedList<>();
  for (File each : findRuleConfigurationFiles(configPath)) {
    Optional<YamlProxyRuleConfiguration> ruleConfig = loadRuleConfiguration(each, serverConfig);
    if (ruleConfig.isPresent()) {
      Preconditions.checkState(schemaNames.add(ruleConfig.get().getSchemaName()), "Schema name `%s` must unique at all rule configurations.", ruleConfig.get().getSchemaName());
      ruleConfigurations.add(ruleConfig.get());
    }
  }
  Preconditions.checkState(!ruleConfigurations.isEmpty() || null != serverConfig.getOrchestration(), "Can not find any sharding rule configuration file in path `%s`.", configPath.getPath());
  Map<String, YamlProxyRuleConfiguration> ruleConfigurationMap = new HashMap<>(ruleConfigurations.size(), 1);
  for (YamlProxyRuleConfiguration each : ruleConfigurations) {
    ruleConfigurationMap.put(each.getSchemaName(), each);
  }
  return new ShardingConfiguration(serverConfig, ruleConfigurationMap);
}

代码示例来源:origin: LMAX-Exchange/disruptor

public void add(
  final EventProcessor eventprocessor,
  final EventHandler<? super T> handler,
  final SequenceBarrier barrier)
{
  final EventProcessorInfo<T> consumerInfo = new EventProcessorInfo<>(eventprocessor, handler, barrier);
  eventProcessorInfoByEventHandler.put(handler, consumerInfo);
  eventProcessorInfoBySequence.put(eventprocessor.getSequence(), consumerInfo);
  consumerInfos.add(consumerInfo);
}

代码示例来源:origin: commons-collections/commons-collections

public Object[] toArray(Object[] array) {
    Collection c = new ArrayList(size());
    for (Iterator it = iterator(); it.hasNext(); ) {
      c.add(it.next());
    }
    return c.toArray(array);
  }
};

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

public Collection<V> values() {
  processQueue();
  Collection<K> keys = map.keySet();
  if (keys.isEmpty()) {
    //noinspection unchecked
    return Collections.EMPTY_SET;
  }
  Collection<V> values = new ArrayList<V>(keys.size());
  for (K key : keys) {
    V v = get(key);
    if (v != null) {
      values.add(v);
    }
  }
  return values;
}

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

if ( !isEscapedSpace )
      result.add( current.toString() );
      current = new StringBuilder();
      continue;
  result.add( current.toString() );
return result.toArray( new String[result.size()] );

代码示例来源:origin: google/guava

@CollectionFeature.Require({SUPPORTS_ADD, FAILS_FAST_ON_CONCURRENT_MODIFICATION})
@CollectionSize.Require(absent = ZERO)
public void testAddConcurrentWithIteration() {
 try {
  Iterator<E> iterator = collection.iterator();
  assertTrue(collection.add(e3()));
  iterator.next();
  fail("Expected ConcurrentModificationException");
 } catch (ConcurrentModificationException expected) {
  // success
 }
}

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

private static void initIncludesAndExcludes() {
  CorePlugin corePlugin = Stagemonitor.getPlugin(CorePlugin.class);
  excludeContaining = new ArrayList<String>(corePlugin.getExcludeContaining().size());
  excludeContaining.addAll(corePlugin.getExcludeContaining());
  excludes = new ArrayList<String>(corePlugin.getExcludePackages().size());
  excludes.add("org.stagemonitor");
  excludes.addAll(corePlugin.getExcludePackages());
  includes = new ArrayList<String>(corePlugin.getIncludePackages().size());
  includes.addAll(corePlugin.getIncludePackages());
  if (includes.isEmpty()) {
    logger.warn("No includes for instrumentation configured. Please set the stagemonitor.instrument.include property.");
  }
}

代码示例来源:origin: apache/incubator-shardingsphere

/**
 * Parse insert values.
 *
 * @param insertStatement insert statement
 */
public void parse(final InsertStatement insertStatement) {
  Collection<Keyword> valueKeywords = new LinkedList<>();
  valueKeywords.add(DefaultKeyword.VALUES);
  valueKeywords.addAll(Arrays.asList(getSynonymousKeywordsForValues()));
  if (lexerEngine.skipIfEqual(valueKeywords.toArray(new Keyword[valueKeywords.size()]))) {
    parseValues(insertStatement);
  }
}

代码示例来源:origin: apache/incubator-pinot

/**
 * Merge two partial results for selection queries without <code>ORDER BY</code>. (Server side)
 *
 * @param mergedRows partial results 1.
 * @param rowsToMerge partial results 2.
 * @param selectionSize size of the selection.
 */
public static void mergeWithoutOrdering(@Nonnull Collection<Serializable[]> mergedRows,
  @Nonnull Collection<Serializable[]> rowsToMerge, int selectionSize) {
 Iterator<Serializable[]> iterator = rowsToMerge.iterator();
 while (mergedRows.size() < selectionSize && iterator.hasNext()) {
  mergedRows.add(iterator.next());
 }
}

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

public boolean put(K key, V method) {
 boolean setExists = true;
 C l = m_objects.get(key);
 if (l == null) {
  setExists = false;
  l = createValue();
  m_objects.put(key, l);
 }
 return l.add(method) && setExists;
}

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

/**
 * Adds all of the Objects returned by the given Iterator into the given Collection.
 *
 * @return the given Collection
 */
public static <T> Collection<T> addAll(Iterator<? extends T> iter, Collection<T> c) {
 while (iter.hasNext()) {
  c.add(iter.next());
 }
 return c;
}

代码示例来源:origin: google/guava

@CollectionSize.Require(absent = ZERO)
@MapFeature.Require(value = SUPPORTS_PUT, absent = ALLOWS_NULL_VALUES)
public void testAddNullValueUnsupported() {
 Collection<V> result = multimap().asMap().get(k0());
 try {
  result.add(null);
  fail("Expected NullPointerException");
 } catch (NullPointerException expected) {
 }
}

代码示例来源:origin: apache/incubator-shardingsphere

/**
 * Load proxy configuration.
 *
 * @return proxy configuration
 * @throws IOException IO exception
 */
public ShardingConfiguration load() throws IOException {
  Collection<String> schemaNames = new HashSet<>();
  YamlProxyServerConfiguration serverConfig = loadServerConfiguration(new File(ShardingConfigurationLoader.class.getResource(CONFIG_PATH + SERVER_CONFIG_FILE).getFile()));
  File configPath = new File(ShardingConfigurationLoader.class.getResource(CONFIG_PATH).getFile());
  Collection<YamlProxyRuleConfiguration> ruleConfigurations = new LinkedList<>();
  for (File each : findRuleConfigurationFiles(configPath)) {
    Optional<YamlProxyRuleConfiguration> ruleConfig = loadRuleConfiguration(each, serverConfig);
    if (ruleConfig.isPresent()) {
      Preconditions.checkState(schemaNames.add(ruleConfig.get().getSchemaName()), "Schema name `%s` must unique at all rule configurations.", ruleConfig.get().getSchemaName());
      ruleConfigurations.add(ruleConfig.get());
    }
  }
  Preconditions.checkState(!ruleConfigurations.isEmpty() || null != serverConfig.getOrchestration(), "Can not find any sharding rule configuration file in path `%s`.", configPath.getPath());
  Map<String, YamlProxyRuleConfiguration> ruleConfigurationMap = new HashMap<>(ruleConfigurations.size(), 1);
  for (YamlProxyRuleConfiguration each : ruleConfigurations) {
    ruleConfigurationMap.put(each.getSchemaName(), each);
  }
  return new ShardingConfiguration(serverConfig, ruleConfigurationMap);
}

相关文章