使用对象的n个克隆创建Java集合 [英] Create java collection with n clones of an object

查看:79
本文介绍了使用对象的n个克隆创建Java集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,有没有一种方法可以创建用对象的 n 个克隆初始化的集合?

In Java, is there a one-line way to create a collection that is initialized with n clones of an object?

I想要与此等效:


  • foo = vector< vector< int> >(10); c ++,创建10个不同的空向量

  • [[] for range(10)中的i] Python,由10个不同的空数组组成的数组

  • Array.new(10){[]} Ruby,与Python一样

  • foo = vector<vector<int> >(10); c++, creates 10 different empty vectors
  • [ [] for i in range(10) ] Python, an array of 10 distinct empty arrays
  • Array.new(10) { [] } Ruby, same as Python

在Java中,我只发现

In Java, I've only found

new ArrayList<ArrayList<Integer> >(Collections.nCopies(10, new ArrayList<Integer>()))

但是与其他示例等效,因为list别名。

However, this is not equivalent to the other examples, because the lists alias.

有没有一种方法可以创建一组不同的对象克隆,而无需使用for循环,最好不要使用外部库

Is there a way to create an array of distinct object clones, without using a for loop, and preferably without resorting to external libraries?

推荐答案

如果您使用的是Java 8,则可以使用其流:

If you're using Java 8 you could use its streams:

Stream.generate(ArrayList<Integer>::new)
    .limit(10).collect(Collectors.toList());

Stream.generate() 方法采用 供应商 知道如何产生一个值并生成这些值的无限流(每个值都是通过再次调用供应商来获得的,因此它们都不同,与 Collections.nCopies())。在流中放置一个 limit(),然后将结果收集到一个列表中,从而产生一个不同条目的列表。

The Stream.generate() method takes a Supplier that knows how to produce a value and generates an infinite stream of those values (each value is obtained by calling the supplier again, so they are all different, unlike Collections.nCopies()). Placing a limit() on the stream and then collecting the results to a list thus yields a list of distinct entries.

这篇关于使用对象的n个克隆创建Java集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆