Set All Values of Arraylist to False on Instantiation
Is There an Ease Way to Create an Arraylist Using Java and Have Them Initially All Set to False Without Looping Through and Assigning Each to False? 4 5...
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?
5 Answers
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));