An ArrayList
class is a resizable array, which is present in the java.util
package.
While built-in arrays have a fixed size, ArrayLists can change their size dynamically. Elements can be added and removed from an ArrayList whenever there is a need, helping the user with memory management.
ArrayLists are similar to vectors in C++:
Below is the syntax for declaring an ArrayList. Similar to arrays, it is required to specify the data type of elements in an ArrayList and it is up to the user to define its initial size.
import java.util.ArrayList; //import the ArrayList classclass MyClass {public static void main( String args[] ) {ArrayList<String> shapes = new ArrayList<String>(); // Create an ArrayList object with a string data type}}
Below are some useful methods in the ArrayList class:
Add an item: The add()
method is used to add an item at the start of an ArrayList. The index of this item is 0
and all other indexes are increased by 1.
shapes.add("hexagon")
Access an item: The get()
method, taking an index as input, is used to access an element in the ArrayList.
shapes.get(3)
Set an item: The set()
method, taking an index as input, is used to set an element in the ArrayList at the specified index.
shapes.set(2, "triangle")
Remove an item: The remove()
method, taking an index as input, is used to remove an element in an ArrayList. Indexes of all the elements in front of the removed element are reduced by 1.
shapes.remove(1)
Remove all items:
The clear()
method is used to remove all elements in an ArrayList.
shapes.clear()
Size of ArrayList:
The size()
method is used to find the number of elements in an ArrayList.
shapes.size()
Below is a Java code for implementation of an ArrayList.
import java.util.ArrayList; // importing the ArrayList Classclass MyClass {public static void main( String args[] ) {ArrayList<String> shapes = new ArrayList<String>(); //create an ArrayList with string data typeshapes.add("square"); // add square at index 0shapes.add("triangle"); // add triangle at index 1shapes.add("hexagon"); // add hexagon at index 2shapes.add("rhombus"); // add rhombus at index 3shapes.add("octagon"); // add octagon at index 4shapes.add("rectangle"); // add rectangle at index 5shapes.add("pentagon"); // add pentagon at index 6System.out.println(shapes); // prints all elements of ArrayList shapesSystem.out.println(shapes.get(4)); // print element at index 4shapes.remove(2); // removing element at index 2shapes.remove(5); // removing element at index 5System.out.println(shapes); // prints all elements of ArrayList shapesshapes.set(4,"circle"); // replaces element at index 4 with circleSystem.out.println(shapes); // prints all elements of ArrayList shapesSystem.out.println(shapes.size()); // prints the number of elements in the ArrayListshapes.clear(); // removes all elements in the ArrayListSystem.out.println(shapes); // prints all elements of ArrayList shapes}}