ArrayList is one of the inbuilt data structures in Java. It is a dynamic array (where the size of the data structure not needed to be declared first) for storing elements (Objects).
It extends AbstractList class and implements List interface. An ArrayList can contain duplicate elements where it maintains insertion order. It should be noted that the class ArrayList is non-synchronized, so care should be taken when handling concurrency with ArrayList. ArrayList allows random access because array works at the index basis. Manipulation is slow in ArrayList because of shifting that often occurs when an element is removed from the array list.
An ArrayList can be created as follows:
List<T> myArrayList = new ArrayList<>();
Where T ( Generics ) is the type that will be stored inside ArrayList.
The type of the ArrayList can be any Object. The type can't be a primitive type (use their wrapper classes instead).
To add an element to the ArrayList, use add() method:
myArrayList.add(element);
Or to add item to a certain index:
myArrayList.add(index, element); //index of the element should be an int (starting from 0)
To remove an item from the ArrayList, use the remove() method:
myArrayList.remove(element);
Or to remove an item from a certain index:
myArrayList.remove(index); //index of the element should be an int (starting from 0)
Giving your list a type
To create a list you need a type (any class, e.g. String). This is the type of your List. The List will only store objects of the specified type. For example:
List<String> strings; Can store "string1", "hello world!", "goodbye", etc, but it can't store 9.2, however:
List<Double> doubles; Can store 9.2, but not "hello world!".
Initialising your list
If you try to add something to the lists above you will get a NullPointerException, because strings and doubles both equal null!
There are two ways to initialise a list:
Option 1: Use a class that implements List
List is an interface, which means that does not have a constructor, rather methods that a class must override. ArrayList is the most commonly used List, though LinkedList is also common. So we initialise our list like this:
List<String> strings = new ArrayList<String>(); or List<String> strings = new LinkedList<String>(); Version ≥ Java SE 7 Starting from Java SE 7, you can use a diamond operator: List<String> strings = new ArrayList<>(); or List<String> strings = new LinkedList<>();
Option 2: Use the Collections class
The Collections class provides two useful methods for creating Lists without a List variable:
And a method which uses an existing List to fill data in:
Examples:
import java.util.List; import java.util.Collections; List
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions