x

Java – Arraylist

Prev     Next

  • ArrayList is a class that implements the List interface.
  • The advantage of ArrayList over the general Array is that ArrayList is dynamic and the size of ArrayList can grow or shrink.
  • ArrayList stores the elements in the insertion order.
  • ArrayList can have duplicate elements. ArrayList is non synchronized.

Creating an ArrayList:

Syntax:


ArrayList obj = new ArrayList(); //Without  Generics

ArrayList<DataType> obj = new ArrayList<Data Type>(); //Using Generics

Example:

ArrayList<String> name = new ArrayList<String>();

Adding elements in the ArrayList:

Elements can be added to an arraylist object by using add() method of the ArrayList class.

Syntax:

add(E e)

To Add an element at a specific index.

Syntax:

add(int index, Element e)

Example:

Output:

Name:Anjali
Name:Anu
Name:Bala
Name:Anu

Removing Element from the ArrayList:

Elements can be removed from an arraylist using remove() method of the ArrayList class.

Syntax:

remove(E e)

The above method removes the first occurrence of the element ‘e’ from the array list.

Syntax:

remove(int index)

The above method removes the element from the index specified in the argument.


Example:

Output:

ArrayList: [Anjali,Anu,Bala,Anu]

Removing element in the position 2:

ArrayList: [Anjali,Anu,Anu]

Removing element ‘Anjali’ from the list:
After Removal..
Anu
Anu

Finding the Length of the ArrayList:

The length of an ArrayList can be found using size() method of the ArrayList class.

Example:

Output:

Names: [Anjali,Anu,Bala,Anu]

Hari added to the list

Names: [Anjal,Anu,Bala,Anu,Hari]

Size after adding an element:5

Methods of ArrayList:

Methods of ArrayList Description
boolean add(E e) Appends the element e to the end of the list.
void add(int i, E element) Inserts the element at the specified index ‘i’ in the list.
void clear() Removes all the elements from the list.
boolean contains(Object o) Returns true if the list contains the object specified.
E get(int index) Returns the element at the specified index in the list.
boolean isEmpty() Checks whether the list is empty. Returns true if the list has no elements
E remove(int index) Removes the element at the specified index in the list.
E set(int index, E element) Replaces the element at the specified index in the list with the element given.
int size() Returns the number of elements in the list.
boolean addAll(Collection<? extends E> c) Appends all of the elements in the specified collection to the end of the list.
boolean removeAll(Collection<?> c) Removes all the elements that are contained in the specified collection from the ArrayList.
List<E> subList(int from, int to) Returns a list which contains the elements between the specified positions. from – inclusive , to – exclusive.

Prev     Next



Like it? Please Spread the word!