Java ArrayList — Java Technical Interview Questions & Answers

Java ArrayList

Java ArrayList

  • ArrayList is a resizable array that implements List. A normal array has a fixed size. ArrayList can grow when you add. Duplicates are allowed. Order is kept — first add stays first. This is the list you use in almost every fresher program.
  • Let’s take this on the board. ArrayList<String> names = new ArrayList<>(); names.add("Asha"); names.add("Ravi"); print names.size(); print names.get(0);. Output: 2 then Asha. Index from 0, same as array. get(1) is Ravi. get(2) throws IndexOutOfBoundsException — last valid index is size() - 1. Don’t write names.get(names.size()).
  • Fast get(i) is why we pick ArrayList day to day. Adding in the middle is slower because later items shift, like inserting a bench in the middle of a row. If you only add at the end and read by index, ArrayList is perfect. If you need unique names, use HashSet. If you insert/delete a lot at both ends, then think LinkedList — not on day one.
  • Cannot store raw int. ArrayList<Integer> marks = new ArrayList<>(); marks.add(90); works because of autoboxing (int → Integer). ArrayList<int> is illegal. Write the type in < >. Raw ArrayList without generics is old style and unsafe.
  ArrayList names
    add("Asha")  add("Ravi")
         │
         ▼
    [0]=Asha  [1]=Ravi   size=2

Technical Interview Tip: Say: resizable array, get(i) is fast. Write add + get + size. Mention Integer not int.

Code Examples for Java ArrayList

Example

import java.util.ArrayList;

// ArrayList demo
public class Main {
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Asha");
    names.add("Ravi");
    System.out.println(names.size());
    System.out.println(names.get(0));
  }
}

Java ArrayList — output: 2 then Asha. add Asha, add Ravi. size is 2. get(0) is Asha. get(2) would throw IndexOutOfBoundsException.

How to Explain Java ArrayList to an Interviewer

What is ArrayList?

Resizable array List Duplicates OK

Can it store int?

Not directly Use Integer

When not ArrayList?

Need unique → HashSet Lots of middle insert → maybe LinkedList