LINKED LIST IN JAVA
Hello guys we are back with another blog in java and today we
are gonna talk about linked list in java. So we are acknowledged with arrays in
java, and linked list are quite similar to arrays in java. They are also non
primitive data types but unlike arrays they are not saved in a contiguous
memory locations where each element of the linked list has the reference or
address of the next element in the linked list. Basically actions such as insertion
and deletion of elements are much easier to perform in linked list that’s why
one can prefer them over arrays.
Now let’s first jump to the basic syntax of how to create a
linked list object and then we will discuss about the method used to add values
inside the linked list.
The basic syntax to create linked list object is written
below.
Syntax:
LinkedList <Type> li = new LinkedList <>();
So in the above syntax we are creating a linked list object named
‘li’ which will be able to store values of whatever type we want.
add() METHOD : The add method is used to add elements
inside the linked list. Suppose we want to add an string element inside our
linked list, whose object is named ‘li’, so the syntax we will be
li.add(“Hello”);
Now the add method can be also used to store the
elements at an specific index. Suppose we want so put our string element at 0th
index so the syntax will be written with the index at which the element is to
be added, followed by that element after a comma.
Example:
li.add(0, “Hello”);
Below is an exemplary code giving complete idea of creating a
linked list, adding elements to it and finally printing it out.
import java.util.*;
public class Linked_List {
public static void main(String[] args) {
LinkedList <String> li= new LinkedList<String>();
li.add("Hello");
li.add("Readers");
li.add("Welcome!");
System.out.println(li);
}
}
//OUTPUT:
[Hello, Readers, Welcome!]
Now below is the example of adding an element at an specific
index.
import java.util.*;
public class Linked_List {
public static void main(String[] args) {
LinkedList <String> li= new LinkedList<String>();
li.add(0,"Welcome!");
li.add("Hello");
li.add(1,"Readers");
System.out.println(li);
}
}
OUTPUT: [Welcome!, Readers, Hello]
That’s all for today guys, we would discuss more about the
Linked list and it’s methods in java. Hope you guys liked it and do let us know
your views in the comment section below.
No comments:
Post a Comment