Set All Values of Arraylist 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?

4

5 Answers

Do like this

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

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.

1

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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest