java – Set all values of ArrayList<Boolean> to false on instantiation-ThrowExceptions

Exception or error:

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?

How to solve:

Do like this

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

###

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.

###

Use Collections.nCopies:

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

###

You could also use the following

Arrays.fill(list, Boolean.FALSE);

###

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

Leave a Reply

Your email address will not be published. Required fields are marked *