Reputation: 1491
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?
Upvotes: 26
Views: 124930
Reputation: 1
first of all we can create a boolean list by ArrayListlist=new ArrayList(size); then u can add by if and else conditions whether it is true or not so list.add(index position,element); as element should be of boolean data type u convert from string to boolean i.e., list.add(index position,Boolean.valueOf(element));
Upvotes: 0
Reputation: 39536
Use Collections.nCopies
:
List<Boolean> list = new ArrayList<>(Collections.nCopies(n, false));
Upvotes: 6
Reputation: 11
ArrayList<Boolean> list = new ArrayList<Boolean>(size);
list.addAll(Collections.nCopies(size, Boolean.FALSE));
Upvotes: 1
Reputation: 2297
You could also use the following
Arrays.fill(list, Boolean.FALSE);
Upvotes: 0
Reputation: 26094
Do like this
List<Boolean> list=new ArrayList<Boolean>(Arrays.asList(new Boolean[10]));
Collections.fill(list, Boolean.TRUE);
Upvotes: 45
Reputation: 30528
You can use the fill
method from Collections
:
Collections.fill(list, Boolean.FALSE);
Another option might be using an array instead of a List
:
boolean[] arr = new boolean[10];
This will auto-initialize to false
since boolean
's default value is false
.
Upvotes: 7