Java ArrayList
In Java, we use the ArrayList class to implement the functionality of resizable-arrays.It implements the List interface of the collections framework.
Creating an ArrayList:
Before using ArrayList, we need to import the java.util.ArrayList package first. Here is how we can create arraylists in Java:
ArrayList<Type> arrayList= new ArrayList<>();
Example: Create ArrayList in Java:
import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create ArrayList
ArrayList<String> languages = new ArrayList<>();
// Add elements to ArrayList
languages.add("Java");
languages.add("Python");
languages.add("Swift");
System.out.println("ArrayList: " + languages);
}
}
Output
ArrayList: [Java, Python, Swift]
Basic Operations on ArrayList:
- Add elements
- Access elements
- Change elements
- Remove elements
Methods of ArrayList Class:
Methods | Descriptions |
---|---|
size() | Returns the length of the arraylist. |
sort() | Sort the arraylist elements. |
clone() | Creates a new arraylist with the same element, size, and capacity. |
contains() | Searches the arraylist for the specified element and returns a boolean result. |
ensureCapacity() | Specifies the total element the arraylist can contain. |
isEmpty() | Checks if the arraylist is empty. |
indexOf() | Searches a specified element in an arraylist and returns the index of the element. |
The important points about the Java ArrayList class are:
- Java ArrayList class can contain duplicate elements.
- Java ArrayList class maintains insertion order.
- Java ArrayList class is non synchronized.
- Java ArrayList allows random access because the array works on an index basis.
- In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list.
- We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class in such cases.
- Java ArrayList gets initialized by the size. The size is dynamic in the array list, which varies according to the elements getting added or removed from the list.