0

I am new to Java and have below code.

List<List<TreeNode>> dp = new ArrayList<List<TreeNode>>(N + 1);
System.out.println(dp.isEmpty());

for (int i = 0; i <= N; i++) {
    dp.set(i, new ArrayList<TreeNode>());
}

dp.isEmpty() returns true; and I have Java.lang.IndexofBoundsException for line dp.set()...

I thought after new.. the dp already has N+1 entries, but it turned out wrong....dp is still empty..

so How can populate dp with N+1 arraylist

halfer
  • 19,824
  • 17
  • 99
  • 186
nathan
  • 754
  • 1
  • 10
  • 24

1 Answers1

2

When you are writing new ArrayList<List<TreeNode>>(N + 1);, this is telling java that create arraylist with initial size of N + 1 elements.

As arraylist is dynamically increases as you add elements this number increases also internally.

Here, N+1 does not mean there are N+1 elements in the List, it just means N+1 memory is allocated by the List.

To add elements you need to do as follows,

for (int i = 0; i <= N; i++) {
    dp.add(i, new ArrayList<TreeNode>());
}

System.out.println(dp.isEmpty()); // false here
Plochie
  • 3,944
  • 1
  • 17
  • 33