Explanation of LinkedList in Java

Explanation of LinkedList in Java

Hello everyone, in this article we are going to talk about LinkedList in Java. We will first see what it is and then we are going to make an example about LinkenList in Java.

Let's get started.

Firstly, What is LinkedList
Linkedlist is a collection class which can hold same type data like Arraylist. In has all functionality as same as Arraylist. They both have List interface. So the developer can add, get and remove the datas from LinkedList.

What is the differance between LinkedList and ArrayList
Arraylist work with a traditional array within it. Arraylists hold the value inside this array and make the operations from this array. During the adding data to arraylist, as we did with below Java 7, it creates new array with bigger size and add it.

LinkedList work with objects in it not with traditional array. It hold the datas as node objects and all the datas linked with an order through adresses. The developer will access the LinkedList orderly.

Now let's write some code about LinkedList in Java.

Firstly make sure the following libraries are imported:

import java.util.ArrayList;
import java.util.LinkedList;
You can add the data to LinkedList with add method.

LinkedList<String> list = new LinkedList<>();
list.add("Burak");
list.add("Hamdi");
list.add("TUFAN");
System.out.println(list);
Output :

[Burak, Hamdi, TUFAN]

You can clear all objects in it with clear method

list.clear();
System.out.println(list);
output :

[]

You can also add data start and end of list. Also you can add data at specified index

list.add("Code");
list.addFirst("The");
list.addLast("Program");
list.add(1, "Clean");
System.out.println(list);
Output :

[The, Clean, Code, Program]

You can remove the data from specified index and specified object

list.remove(1);
System.out.println("Removed from index : " + list);
        
list.remove("Program");
System.out.println("Removed object : " + list);
Output :

Removed from index : [The, Code, Program]
Removed object : [The, Code]

You can initialize a linkedlist from arraylist and with its elements

ArrayList<Integer> arr = new ArrayList<>();
for(int i=0; i<10; i++){
     arr.add(i);
}
        
LinkedList intList = new LinkedList(arr);
System.out.println(intList);
Output :

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can get the data from index, first or last data

System.out.println(intList.get(5));
System.out.println(intList.getFirst());
System.out.println(intList.getLast());
Output :

5
0
9

That is all in this article.

Burak Hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment.

Comments

  • There is no comment. Be the owner of first comment...