ArrayList- Java
Dynamic array in java is called as ArrayList. ArrayList class extends AbstractList ,which implements List class, where List class extends Collection and Collection extends Iterable. ArrayList is more flexible than inbuild Array data structure.
It is very to access, insert, remove, change elements in ArrayList.
Let us see the declaration of an ArrayList.
ArrayList<E> arrayList = new ArrayList<E>
E is the datatype of the elements which we want to insert in the arrayList.
Methods used in ArrayList:
- Inserting:
a. void add(E element) : It is used to add a new element at the last of the ArrayList.
b. void add(int index, E element) : It is used to add a new element at given index in the ArrayList.
c. boolean addAll(Collection c) : It appends a group of elements at the last of the index in the ArrayList. It returns true, if they are appended else returns false.
d. boolean addAll(int index, Collection c) : It returns true , if the list is appended at the specified position else returns false.
2.Removing :
a. E remove (int index) : It removes an element at specified index from the ArrayList.
b. void clear() : It removes all the elements from the list.
c. boolean remove(Object o) : It is used to remove the Object at the first occurrence in the list and returns true . If the object is not in the list, then it returns false.
3.Accessing:
a. E get(int index) : It fetches the element at the given index.
b. List<E> subList(int fromIndex, int toIndex) : It fetches the sublist from start index to end index.
4.Changing the element:
a. E set(int index, E element): It replaces the old element at given position to the new element.
5.Sorting:
a. void sort(List<E> list) : It is method from Collection class which sorts the elements in ascending order.
6. Other methods:
a. boolean isEmpty() : It returns true , if the list is empty else returns false.
b. int indexOf(Object o) : It returns the index of the first occurrence of the object. If the object does not exist, then it returns -1.
c. int lastIndexOf(Object o) : It returns the index of the last occurrence of the object in the list. It returns -1 if there is no object.
Let us see the implementation of these methods.
These are the most used methods in ArrayList.
Thanking You.