创建带有重复元素的列表 [英] Creating a list with repeating element

查看:47
本文介绍了创建带有重复元素的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中是否存在一种实用程序方法,该方法可以生成具有指定长度的列表或数组,并且所有元素都等于指定值(例如["foo","foo","foo","foo","foo"])?

Is there an utility method in Java that generates a list or array of a specified length with all elements equal to a specified value (e.g ["foo", "foo", "foo", "foo", "foo"])?

推荐答案

您可以使用

You can use Collections.nCopies. Note that this copies the reference to the given object, not the object itself. If you're working with strings, it won't matter because they're immutable anyway.

List<String> list = Collections.nCopies(5, "foo");
System.out.println(list);


[foo, foo, foo, foo, foo]

这篇关于创建带有重复元素的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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