ArrayList in Java || Java and DSA course || Blog 10
We know what is an Array. An array is a collection of similar data elements stored at contiguous memory locations. It has a fixed size.
If we want to add value to our array whose current size is 7 and elements present are 7, its not possible. Even if we don't have continuous memory, we cannot make an array.
These were some drawbacks of Array. ArrayList solves this drawbacks.ArrayList connects to each memory. It is non-continuous. the size of ArrayList is a variable. it change according to us. It can store Primitive Data type and Objects. To know more about Primitive Data types, visit:-
https://unnatikadamjavadsa.blogspot.com/2022/06/data-types-in-java-java-dsa-course-blog.html
ArrayList is a part of collection framework
For a quick overview we will be learning about :
- add
- get
- insert
- set
- delete
- size
- loops/iterate
- sorting
We need to import package named as java.util.ArrayList
To make an ArrayList we use,
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1 is the name, integer the type of array new is the keyword to make ArrayList.
Add
The output will be
Here we use .add function to add integer . their index depends when they are added.
Get
We try to get one of the integer in array using index of the value. lets say we want the number present on index 1(which is 12)
The output will be 12. we used the .get() here.
Insert
Lets say we want to insert our 22 at index 1 where 12 is there.
The output will be
We passed our index value and our number in .add()
Set
Now we dont to insert our element, instead we want to change 22 with 32
The output will be
Delete
Lets remove 32 from list
The output will be:
Here we use .remove() and pass the index which we want to remove.
Size
Right now , how much elements do we have in total. we can use .size() to find out.
It will print 3
Loops
We are going to use loop to print our array
The output is
Sorting
in ArrayList we have a .sort() function which sorts our list.
We need to import java.util.Collections
The output is:
This was all about ArrayList which we will be using in Data Strucures and algorithms.
__________________________________________________________________________________
Checkout:https://javaanddsa.blogspot.com/
Did you like our blog 10??
👍👍👍👍👍👍
ReplyDelete