Allan Macmillan
Allan Macmillan

Reputation: 1491

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

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

Answers (6)

user22075743
user22075743

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

ZhekaKozlov
ZhekaKozlov

Reputation: 39536

Use Collections.nCopies:

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

Upvotes: 6

Dill
Dill

Reputation: 11

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

Upvotes: 1

Gaurav Sarma
Gaurav Sarma

Reputation: 2297

You could also use the following

Arrays.fill(list, Boolean.FALSE);

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

Do like this

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

Upvotes: 45

Adam Arold
Adam Arold

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

Related Questions