To overcome this we can implement Arraylist in Java.
For more updates do like our Facebook page.
What is an ArrayList?
In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists
would increase in size when objects are added and shrinks as objects are removed similar to Dictionary object in VBscript.
We use ArrayList incase we are not sure on the upper bound on the number of elements. On the other side, a simple Array in java is a static data structure,
because the initial size of array cannot be changed, meaning it can be used only when the data has a known number of elements.
How to use it?
By calling the ArrayList constructor.
- ArrayList( ) -- An Array without any initial capacity
- ArrayList(Collection c) -- It creates a list containing the elements of the specified collection
- ArrayList(int capacity)--An Array with initial capacity
To create an array list in Java, we need declare an ArrayList variable (Learn) and call the ArrayList constructor to instantiate an ArrayList object and
assign it to the variable. We have taken 10 as the initial size of an Arraylist.
|Methods in ArrayList|
Adding Elements to Arraylist:-
We need to use the Add() method to add object(element) to the array list.
Incase we have specified a type of an Arraylist,the objects that we add via the add method must be of the correct type.
|Adding Int element to Arraylist of String Type|
We can insert an object at a specific position in the list by listing the position in the add method
Updating value of ArrayList:-
We need to use Set method for the same,
Deleting Elements in ArrayList:-
To remove all the elements, use the clear method:
To remove a specific element based on the index number, use the remove method:
Incase we don’t know the index of the object we want to remove, we can remove it by using the reference name,
Count of elements in Arraylist:-
We call the size() method on the ArrayList instance. This returns the number of elements in the collection.
How to fetch element value from a given index:-
We use get() method, which receives the index of the element to get.
we can loop and iterate to get the value in each element of the arraylist.
Collections.sort. We can sort an ArrayList with this method. This method sorts in ascending (low to high) order.
- Creating ArrayList by using Add Method
- Displaying ArrayList
- Further using Index to Add elements into ArrayList
- Using Get Method
- And getting the Size of Arraylist.
- Removing particular Element from Arraylist --Remove method
- Deleting all the elements of Arraylist--Clear method
- Shuffle Arraylist elements
- Sort Arraylist
- Convert Arraylist into Array