Java中是否有一种实用程序方法可以生成具有指定长度的列表或数组,且所有元素都等于指定值(例如[“ foo”,“ foo”,“ foo”,“ foo”,“ foo”])?
Answers:
您可以使用Collections.nCopies。请注意,这会将引用复制到给定的对象,而不是对象本身。如果您使用的是字符串,则没关系,因为它们始终是不可变的。
List<String> list = Collections.nCopies(5, "foo");
System.out.println(list);
[foo,foo,foo,foo,foo]
对于数组,可以使用Arrays.fill(Object [] a,Object val)
String[] strArray = new String[10];
Arrays.fill(strArray, "foo");
如果您需要列表,请使用
List<String> asList = Arrays.asList(strArray);
然后,我必须使用两行:String [] strArray = new String [5]; Arrays.fill(strArray,“ foo”);。有单线解决方案吗?
您可以使用Collections.nCopies(5,“ foo”)作为单行解决方案来获取列表:
List<String> strArray = Collections.nCopies(5, "foo");
或与之结合toArray以获得数组。
String[] strArray = Collections.nCopies(5, "foo").toArray(new String[5]);
String[] strArray = new String[5]; Arrays.fill(strArray, "foo");。有单线解决方案吗?