ArrayList constructor Java

This article is part of ArrayList class series. In this article, we will look at 3 different constructors provided in ArrayList class.

ArrayList class is a better form of an array. ArrayList is an array, but a resizable one, with a rich set of methods.

A little about ArrayList.

  1. Resizable array
    1. ArrayList is a resizable array. As you add the elements in the ArrayList, it grows internally to accommodate those elements. Converse is not true as of JDK 12 i.e. if you delete an element from ArrayList it doesn’t automatically shrink the size of ArrayList. You can manually shrink the size using trimToSize[] method.
  2. Insertion order
    1. ArrayList always maintains Insertion order of elements. Which means if you iterate through the List, the elements will be retrieved in the same order we inserted them.
  3. Positional/Index Access
    1. We know arrays for its index access, so you can access the element in O[1] time. You can achieve the same in ArrayList using get[index] method.
  4. Duplicate elements allowed
    1. ArrayList allows duplicate elements. It doesn’t check if elements exist. It will just append the element it got.
  5. Not thread safe
    1. ArrayList is not a thread safe class. So it is not an ideal candidate to use in a multithreaded environment if data in ArrayList needs to be manipulated.

2. Content

We will look at the working of all these constructors with examples.

public ArrayList[] public ArrayList[int initialCapacity] public ArrayList[Collection

Chủ Đề