ArrayList in Java: Methods
- The ArrayList class is the dynamic array found in the java.util package.
- The size of the normal array can not be changed, but ArrayList provides us the ability to increase or decrease the size.
- ArrayList is slower than the standard array, but it helps us to manipulate the data easily.
How to declare an ArrayList :
Performing various operations on ArrayList :
ArrayList comes with a number of methods that can be used to
manipulate the data of the ArrayList. Let’s take a look at some of the
important methods of ArrayList :
-
Adding an element :
- add() method is used to insert an element in the ArrayList.
- add(Object): Inserts an element at the end of the ArrayList.
- add(Index,Object) : Inserts an element at the given index.
Example :
Output :
Removing an Element :
- remove() method is used to delete or remove an element at a given index from the ArrayList.
Syntax :
Example :
Output :
Checking if an ArrayList contains a specific value or not :
- contains() method is used to check if an ArrayList contains a specified element or not. This method returns the boolean value.
Example :
Output :
Merging two ArrayLists :
- The elements of an ArrayList can be merged into another Arraylist with the help of the addAll() method.
Example :
Output :
Finding the first occurrence of a specified number in the ArrayList :
-
Indexof() method prints the index of the first occurrence of a particular number. Returns -1 if the element is not present in the ArrayList.
Example :
Output :
Similarly, you can also find the index of the last occurrence of an element with the help of the lastIndexOf() method.
No comments:
Post a Comment