+91 81900 98289

Java ArrayList

ArrayList stores items in order and grows when you add. The type in angle brackets says what it holds. ArrayList<String> refuses an int unless you wrap it. get, set, remove, and size are the methods you need first.

An ArrayList is better than an array when you do not know the final count, such as names read from a file. An array is better when the size is fixed and you want the lower overhead.

Example

size is 2 after two adds. Index 1 is Arun, the second name.

import java.util.ArrayList; public class Names { public static void main(String[] args) { ArrayList<String> names = new ArrayList<>(); names.add("Meera"); names.add("Arun"); System.out.println(names.size()); System.out.println(names.get(1)); } }
remove(0) shifts later items left. For a long list and frequent removals from the front, a LinkedList can be a better structure. For most class work, ArrayList is the right default.