Java 用 n 个值的列表扩展 arraylist

标签 java python list arraylist extend

在 python 中,我可以执行以下操作:

n = 8  
a = []  
a += [1]*n

我如何在 java 中用 ArrayLists 做同样的事情(不使用 for 循环..)?

List<T> list = new ArrayList<T>();
list.add(1);
list.add(2);
list.add(3);
// Some construct that is equivalent to a += [1]*n

最佳答案

final List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.addAll(Collections.nCopies(8, 1));

参见 Collections.nCopies()

关于Java 用 n 个值的列表扩展 arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20138275/

相关文章:

python - Django Sphinx 自动模块——基础知识

python - 将元组列表转换为深层嵌套列表

python - python程序中出现 "List Reversing"错误

java - Hibernate中连续命名参数问题(Spring HibernateTemplate)

java - 为什么 Ant 认为我有一个旧版本的 Java?

python - 自定义数组类中 python/pygame 中运算符重载的一些问题

python - 安装时将 git hash 嵌入到 python 文件中

python-2.7 - 在 Python 2.7 中使用 `scandir`

Java getRuntime.exec() - 错误流中的 "Fatal error: no such file or directory"(无异常(exception))

java - Gradle 6 : get the list of implementation dependencies programmatically