Java Code Examples for java.util.Collections.nCopies()

The following are Jave code examples for showing how to use nCopies() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: JarURLStreamHandlerTest.java   View Source Code Vote up 6 votes
@Override
protected void setUp() throws Exception {
    super.setUp();
    clearWorkDir();
    
    jar = new File(getWorkDir(), "x.jar");
    JarOutputStream os = new JarOutputStream(
        new FileOutputStream(jar)
    );
    os.putNextEntry(new ZipEntry("fldr/plain.txt"));
    os.write("Ahoj\n".getBytes());
    os.closeEntry();
    os.close();
    JarClassLoader registerJarSource = new JarClassLoader(
        Collections.nCopies(1, jar),
        new ClassLoader[] { getClass().getClassLoader() }
    );
    assertNotNull("Registered", registerJarSource);
}
 
Example 2
Project: incubator-netbeans   File: ProxyClassPackagesTest.java   View Source Code Vote up 6 votes
public void testMetaInfServicesPackageNotListedByDefault() throws Exception {
    File jar = new File(getWorkDir(), "non-empty.jar");
    TestFileUtils.writeZipFile(jar, 
        "META-INF/services/java.lang.Runnable:1"
    );
    JarClassLoader l1 = new JarClassLoader(Collections.nCopies(1, jar), new ClassLoader[] {
        ClassLoader.getSystemClassLoader()
    });
    
    Set<ProxyClassLoader> set = ProxyClassPackages.findCoveredPkg("META-INF.services");
    assertNull("No JAR covers META-INF.services: " + set, set);

    ProxyClassLoader l2 = new ProxyClassLoader(new ProxyClassLoader[] { l1 }, true);

    Enumeration<URL> en = l2.getResources("META-INF/services/java.lang.Runnable");
    assertTrue("Some are there", en.hasMoreElements());
    URL one = en.nextElement();
    assertFalse("And that is all", en.hasMoreElements());
    
    URL alternative = l2.getResource("META-INF/services/java.lang.Runnable");
    assertEquals("Same URL", one, alternative);
    
    ProxyClassPackages.removeCoveredPakcages(l1);
}
 
Example 3
Project: incubator-netbeans   File: VisualizerNodeTest.java   View Source Code Vote up 6 votes
public void testLazyVisDestroy() throws Exception {
    LazyChildren lch = new LazyChildren();
    AbstractNode a = new AbstractNode(lch);
    List<String> arr = Collections.nCopies(100, "A");
    lch.keys(arr.toArray(new String[0]));

    TreeNode ta = Visualizer.findVisualizer(a);
    final TreeNode snd = ta.getChildAt(2);

    Reference<Node> sndNode = new WeakReference<Node>(Visualizer.findNode(snd));

    assertEquals("Child check", "A", snd.toString());
    assertEquals("Counter should be 1", 1, lch.cnt);

    a.destroy();

    assertGC("Whole subtree under a can be GCed now", sndNode);
}
 
Example 4
Project: incubator-netbeans   File: J2SEProject.java   View Source Code Vote up 6 votes
@Override
@NonNull
public List<DataObject> sort(@NonNull final List<DataObject> original) {
    if (!isLibrary()) {
        return original;
    }
    final List<DataObject> result = new ArrayList<>(Collections.<DataObject>nCopies(CAT_MAP.size(), null));
    for (DataObject dobj : original) {
        final String name = dobj.getName();
        final Integer index = CAT_MAP.get(name);
        if (index == null) {
            result.add(dobj);
        } else {
            result.set (index, dobj);
        }
    }
    return filterNulls(result);
}
 
Example 5
Project: JRediClients   File: LogHelperTest.java   View Source Code Vote up 6 votes
@Test
public void toStringWithSmallCollections() {
    List<String> strings = Collections.nCopies(1, "0");
    List<Integer> ints =  Collections.nCopies(1, 1);
    List<Long> longs =  Collections.nCopies(1, 2L);
    List<Double> doubles =  Collections.nCopies(1, 3.1D);
    List<Float> floats =  Collections.nCopies(1, 4.2F);
    List<Byte> bytes =  Collections.nCopies(1, (byte)5);
    List<Character> chars =  Collections.nCopies(1, '6');
    
    assertThat(LogHelper.toString(strings), is("[0]"));
    assertThat(LogHelper.toString(ints), is("[1]"));
    assertThat(LogHelper.toString(longs), is("[2]"));
    assertThat(LogHelper.toString(doubles), is("[3.1]"));
    assertThat(LogHelper.toString(floats), is("[4.2]"));
    assertThat(LogHelper.toString(bytes), is("[5]"));
    assertThat(LogHelper.toString(chars), is("[6]"));
}
 
Example 6
Project: javaide   File: CreateListOfNCopiesExample.java   View Source Code Vote up 6 votes
public static void main(String[] args) {

    /*
      To create a List containing n copies of specified Object use,
      static List nCopies(int n, Object obj) method of Java Collections class.

      This method returns immutable List containing n copies of the
      specified Object.
    */

    List list = Collections.nCopies(5, "A");

    //iterate through newly created list
    System.out.println("List contains, ");
    Iterator itr = list.iterator();

    while (itr.hasNext()) System.out.println(itr.next());
  }
 
Example 7
Project: grift   File: ThriftUtilsTest.java   View Source Code Vote up 5 votes
@Test
public void testLarge() throws Exception {
  Message m = new Message();
  // list size 80 MB
  m.l = new ArrayList<Integer>(Collections.nCopies(20 * 1024 * 1024, 1000000007));
  Message m2 = marshaller.parse(marshaller.stream(m));
  assertNotSame(m, m2);
  assertEquals(m.l.size(), m2.l.size());
}
 
Example 8
Project: openjdk-jdk10   File: ArrayBlockingQueueTest.java   View Source Code Vote up 5 votes
/**
 * Initializing from too large collection throws IllegalArgumentException
 */
public void testConstructor_collectionTooLarge() {
    // just barely fits - succeeds
    new ArrayBlockingQueue(SIZE, false,
                           Collections.nCopies(SIZE, ""));
    try {
        new ArrayBlockingQueue(SIZE - 1, false,
                               Collections.nCopies(SIZE, ""));
        shouldThrow();
    } catch (IllegalArgumentException success) {}
}
 
Example 9
Project: Proyecto-DASI   File: BuildBattleDecoratorImplementation.java   View Source Code Vote up 5 votes
/**
 * Attempt to parse the given object as a set of parameters for this handler.
 *
 * @param params the parameter block to parse
 * @return true if the object made sense for this handler; false otherwise.
 */
@Override
public boolean parseParameters(Object params)
{
    if (params == null || !(params instanceof BuildBattleDecorator))
        return false;

    this.params = (BuildBattleDecorator) params;

    this.sourceBounds = this.params.getGoalStructureBounds();
    this.destBounds = this.params.getPlayerStructureBounds();
    this.delta = new Vec3i(destBounds.getMin().getX() - sourceBounds.getMin().getX(),
                           destBounds.getMin().getY() - sourceBounds.getMin().getY(),
                           destBounds.getMin().getZ() - sourceBounds.getMin().getZ());
    
    this.structureVolume = volumeOfBounds(this.sourceBounds);
    assert(this.structureVolume == volumeOfBounds(this.destBounds));
    this.dest = new ArrayList<IBlockState>(Collections.nCopies(this.structureVolume, (IBlockState)null));
    this.source = new ArrayList<IBlockState>(Collections.nCopies(this.structureVolume, (IBlockState)null));
    
    DrawBlockBasedObjectType tickBlock = this.params.getBlockTypeOnCorrectPlacement();
    DrawBlockBasedObjectType crossBlock = this.params.getBlockTypeOnIncorrectPlacement();

    this.blockTypeOnCorrectPlacement = (tickBlock != null) ? new XMLBlockState(tickBlock.getType(), tickBlock.getColour(), tickBlock.getFace(), tickBlock.getVariant()) : null;
    this.blockTypeOnIncorrectPlacement = (crossBlock != null) ? new XMLBlockState(crossBlock.getType(), crossBlock.getColour(), crossBlock.getFace(), crossBlock.getVariant()) : null;
    return true;
}
 
Example 10
Project: openjdk-jdk10   File: BigArityTest.java   View Source Code Vote up 5 votes
static MethodHandle MH_hashArguments(Class<? extends Object[]> arrayClass, int arity) {
    if (arrayClass == Object[].class)
        return MH_hashArguments(arity);
    ArrayList<Class<?>> ptypes = new ArrayList<>(Collections.<Class<?>>nCopies(arity, arrayClass.getComponentType()));
    MethodType mt = MethodType.methodType(Object.class, ptypes);
    return MH_hashArguments_VA.asType(mt);
}
 
Example 11
Project: ta4j   File: CashFlowTest.java   View Source Code Vote up 5 votes
@Test
public void reallyLongCashFlow() {
    int size = 1000000;
    TimeSeries sampleTimeSeries = new MockTimeSeries(Collections.nCopies(size, (Tick) new MockTick(10)));
    TradingRecord tradingRecord = new BaseTradingRecord(Order.buyAt(0), Order.sellAt(size - 1));
    CashFlow cashFlow = new CashFlow(sampleTimeSeries, tradingRecord);
    assertDecimalEquals(cashFlow.getValue(size - 1), 1);
}
 
Example 12
Project: javaOIDCMsg   File: ConcurrentVerifyTest.java   View Source Code Vote up 5 votes
@SuppressWarnings("Convert2Lambda")
private void concurrentVerify(final JWT jwt, final String token) throws TimeoutException, InterruptedException {
    final Waiter waiter = new Waiter();
    List<VerifyTask> tasks = Collections.nCopies(REPEAT_COUNT, new VerifyTask(waiter, jwt, token));
    executor.invokeAll(tasks, TIMEOUT, TimeUnit.MILLISECONDS);
    waiter.await(TIMEOUT, REPEAT_COUNT);
}
 
Example 13
Project: Programming-Languages-Lab   File: SearchFileTask.java   View Source Code Vote up 5 votes
/**
 * Searches the tokens in the words given taking into account their relative positioning.
 *
 * @param words words to search from
 */
private void search(List<String> words) {
    int minDistance = Integer.MAX_VALUE, startTokenIndex = 0;

    while (startTokenIndex < words.size()) {
        List<Integer> tokenIndexes = new ArrayList<>(Collections.nCopies(tokens.size(), -1));
        int subListTokenIndex = words.subList(startTokenIndex, words.size()).indexOf(tokens.get(0));
        int newTokenIndex = subListTokenIndex + startTokenIndex;
        tokenIndexes.set(0, newTokenIndex);
        if (subListTokenIndex == -1) {
            break;
        }
        for (int i = 1; i < tokens.size(); ++i) {
            subListTokenIndex = words.subList(newTokenIndex + 1, words.size()).indexOf(tokens.get(i));
            if (subListTokenIndex == -1) {
                break;
            }
            newTokenIndex = subListTokenIndex + newTokenIndex + 1;
            tokenIndexes.set(i, newTokenIndex);
        }
        if (subListTokenIndex == -1) {
            break;
        }
        int minDistanceCandidate = tokenIndexes.get(tokenIndexes.size() - 1) - tokenIndexes.get(0);
        if (minDistanceCandidate < minDistance) {
            minDistance = minDistanceCandidate;
            result.tokenIndexes = tokenIndexes;
        }
        startTokenIndex = tokenIndexes.get(0) + 1;
    }
}
 
Example 14
Project: oma-riista-android   File: GameDatabase.java   View Source Code Vote up 4 votes
public Statistics() {
    mMonthlyData = new ArrayList<>(Collections.nCopies(12, 0));
    mCategoryData = new SparseIntArray();
}
 
Example 15
Project: rapidminer   File: AbstractLogModel.java   View Source Code Vote up 4 votes
public CircularArrayList(int capacity) {
	n = capacity + 1;
	buf = new ArrayList<E>(Collections.nCopies(n, (E) null));
}
 
Example 16
Project: Lagerta   File: MergeUtilUnitTest.java   View Source Code Vote up 4 votes
@Test
public void mergeEvenCountOfListsInBuffer() {
    List<List<Long>> buffer = Collections.nCopies(258, list());
    MergeUtil.mergeCollections(list(), buffer, LONG_COMPARATOR);
    assertEquals(list(), list());
}
 
Example 17
Project: mycat-src-1.6.1-RELEASE   File: CircularArrayList.java   View Source Code Vote up 4 votes
public CircularArrayList(int capacity) {
    n = capacity + 1;
    buf = new ArrayList<E>(Collections.nCopies(n, (E) null));
}
 
Example 18
Project: loom   File: BaseAdapter.java   View Source Code Vote up 4 votes
/**
 * Create a pattern definition for a single input thread.
 *
 * @param id pattern id
 * @param itemTypes item types
 * @param description description
 * @param maxFibres max fibres
 * @param defaultPattern is this a default pattern
 * @param metrics names of the default metrics to be loaded when pattern is first loaded
 * @return the pattern definition
 */
public PatternDefinition createPatternDefinitionWithSingleInputPerThread(final String id,
        final List<ItemType> itemTypes, final String description, final List<Integer> maxFibres,
        final boolean defaultPattern, final List<String> metrics) {

    if (maxFibres != null && itemTypes.size() != maxFibres.size()) {
        throw new IllegalArgumentException(
                "itemTypes (" + itemTypes.size() + ") & maxFibres (" + maxFibres.size() + " sizes should match");
    }

    List<Integer> fibreList;
    if (maxFibres == null) {
        fibreList = Collections.nCopies(itemTypes.size(), 0);
    } else {
        fibreList = maxFibres;
    }

    List<ThreadDefinition> threadDefs = new ArrayList<>(itemTypes.size());
    Map<String, ItemType> itMap = new HashMap<>(itemTypes.size());
    int threadIdx = 0;
    for (ItemType it : itemTypes) {
        List<String> ins = new ArrayList<String>(1);
        ins.add(getAggregationLogicalIdForPattern(it.getLocalId()));
        QueryDefinition query;
        if (fibreList.get(threadIdx) == 0) {
            query = new QueryDefinition(ins);
        } else {
            Map<String, Object> braidParams = new HashMap<String, Object>(1);
            braidParams.put(QueryOperation.MAX_FIBRES, fibreList.get(threadIdx));
            Operation braidOperation = new Operation(DefaultOperations.BRAID.toString(), braidParams);
            List<Operation> braidPipe = new ArrayList<>(1);
            braidPipe.add(braidOperation);
            query = new QueryDefinition(braidPipe, ins);
        }
        ThreadDefinition threadDefinition = new ThreadDefinition(id + "-" + Integer.toString(threadIdx++),
                it.getId(), query, createHumanReadableThreadName(it));
        threadDefs.add(threadDefinition);
        itMap.put(it.getId(), it);
    }

    PatternDefinition pd = new PatternDefinition(id, threadDefs, provider.getProviderType(), new Meta(itMap),
            description, metrics);
    pd.setDefaultPattern(defaultPattern);

    return pd;
}
 
Example 19
Project: bullet-kafka   File: KafkaPubSub.java   View Source Code Vote up 4 votes
@Override
public List<Publisher> getPublishers(int n) throws PubSubException {
    // Kafka Publishers are thread safe and can be reused
    return Collections.nCopies(n, getPublisher());
}
 
Example 20
Project: SparkSeq   File: GATKVariantContextUtils.java   View Source Code Vote up 3 votes
/**
 * Returns a homozygous call allele list given the only allele and the ploidy.
 *
 * @param allele the only allele in the allele list.
 * @param ploidy the ploidy of the resulting allele list.
 *
 * @throws IllegalArgumentException if {@code allele} is {@code null} or ploidy is negative.
 *
 * @return never {@code null}.
 */
public static List<Allele> homozygousAlleleList(final Allele allele, final int ploidy) {
    if (allele == null || ploidy < 0)
        throw new IllegalArgumentException();

    // Use a tailored inner class to implement the list:
    return Collections.nCopies(ploidy,allele);
}