Java 在实例化时将 ArrayList<Boolean> 的所有值设置为 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20615448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:09:08  来源:igfitidea点击:

Set all values of ArrayList<Boolean> to false on instantiation

javaandroid

提问by Allan Macmillan

Is there an ease way to create an ArrayList<Boolean>using Java and have them initially all set to false without looping through and assigning each to false?

有没有一种简单的方法来创建一个ArrayList<Boolean>使用 Java 并将它们最初全部设置为 false 而不循环遍历并将每个分配给 false 的方法?

采纳答案by Prabhakaran Ramaswamy

Do like this

这样做

List<Boolean> list=new ArrayList<Boolean>(Arrays.asList(new Boolean[10]));
Collections.fill(list, Boolean.TRUE);

回答by Adam Arold

You can use the fillmethod from Collections:

您可以使用以下fill方法Collections

Collections.fill(list, Boolean.FALSE);

Another option might be using an array instead of a List:

另一种选择可能是使用数组而不是一个List

boolean[] arr = new boolean[10];

This will auto-initialize to falsesince boolean's default value is false.

这将自动初始化为,false因为boolean的默认值为false

回答by Gaurav Sarma

You could also use the following

您还可以使用以下

Arrays.fill(list, Boolean.FALSE);

回答by Dill

ArrayList<Boolean> list = new ArrayList<Boolean>(size);
list.addAll(Collections.nCopies(size, Boolean.FALSE));

回答by ZhekaKozlov

Use Collections.nCopies:

使用Collections.nCopies

List<Boolean> list = new ArrayList<>(Collections.nCopies(n, false));