使用对象的n个克隆创建Java集合

编程入门 行业动态 更新时间:2024-10-19 22:43:06
本文介绍了使用对象的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]
  • 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集合

本文发布于:2023-11-30 04:20:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648702.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!