Sobes.tech
Junior — Middle

Kui palju elemente võib ArrayList sisaldada selle loomisel ilma suurust määramata?

sobes.tech AI

Vastus AI-lt

Creating an ArrayList in Java without specifying the initial size results in the internal array being initially empty (size 0).

Only when the first element is added does the ArrayList create an internal array with the default size, which is usually 10.

This means:

  • When calling new ArrayList<>(), the internal array is not allocated immediately.
  • When adding the first element, an array of size 10 is allocated.

This helps save memory if the list remains empty.

Example:

ArrayList<String> list = new ArrayList<>();
// internal array is not yet allocated
list.add("First element");
// now the internal array has size 10