3

Following line will initialize arraylist with 9 elements with value true.

public ArrayList<Boolean> timeTable = new ArrayList<Boolean>(Collections.nCopies(9, true));

But how can i initialize arraylist of arraylist?

public ArrayList<ArrayList<Boolean>> timeTable = new ArrayList<ArrayList<Boolean>>(Collections.nCopies(9, true));

It should mean that outer arraylist has 9 inner arraylist and each inner arraylist has 9 elements with true value.

Similar to How can I initialize an ArrayList with all zeroes in Java? But not exactly same...

Scenario is that i need to maintain a monthly list of daily timetables. Now daily timetable will have only 9 entries, so immutable is fine. But monthly list needs to be appended each month. So it can't be an arraylist.

2 Answers 2

7

Given this line form java docs: "Returns an immutable list consisting of n copies of the specified object"

public ArrayList<Boolean> timeTable = new ArrayList<Boolean>(Collections.nCopies(9, true));

public ArrayList<ArrayList<Boolean>> timeTableLists = new ArrayList<ArrayList<Boolean>>(Collections.nCopies(9, timeTable));
Sign up to request clarification or add additional context in comments.

2 Comments

Scenario is that i need to maintain a monthly list of daily timetables. Now daily timetable will have only 9 entries, so immutable is fine. But monthly list needs to be appended each month. So it can't be an arraylist.
So you're saying that timeTableList should be mutable. Than you need to use a for loop
4

Firstly, it is recommended to use interface types wherever possible. That would make your

ArrayList<ArrayList<Boolean>> -> List<List<Boolean>>. 

Then, the initialization statement would become

public List<List<Boolean>> timeTable = Collections.nCopies(9, (Collections.nCopies(9, true)));

3 Comments

No guarantee that nCopies returns an ArrayList if that was a requirement.
Completely agree, but I doubted if ArrayList was really a requirement and List wouldn't suffice here.
Scenario is that i need to maintain a monthly list of daily timetables. Now daily timetable will have only 9 entries, so immutable is fine. But monthly list needs to be appended each month. So it can't be an arraylist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.