LinkedList in Java
June 22, 2017
Categorised in: Java Codes
- Header: java.util.LinkedList<E> (where E denotes the type of elements in the collection)
- Some of the useful methods:
- addFirst(E e)
- addLast(E e)
- clear()
- clone() – returns a shallow copy of the Linked List
- contains(Object o) – returns true if list contains the object
- get(int position)
- getFirst()
- getLast()
- indexOf(Object o)
- remove() – retrieves and removes the head of the list
- remove(Object o) – removes first occurrence of the object o.
- removeFirst()
- removeLast()
- set(int position, E e)
- size()
- toArray()
EXAMPLE
import java.util.*;
import java.io.*;
class Book {
int id;
String name;
public Book(int id, String name) {
this.id = id;
this.name = name;
}
}
public class JavaLinkedList {
public static void main( String []args) {
//Creating list of type Book which is our custom data type now through class
LinkedList<Book> list = new LinkedList<Book>();
Book b1 = new Book(1, "To kill a mocking bird");
Book b2 = new Book(2, "Java for Beginners");
list.add(b1);
list.add(1, b2);
for(Book b: list)
System.out.println(b.id + " " + b.name);
/*
Another way to print:
Iterator<String> itr = list.iterator();
while( itr.hasNext() )
System.out......
*/
}
}
/*
OUTPUT:
1 To kill a mocking bird
2 Java for Beginners
*/
MORE FUNCTIONS
import java.util.*;
import java.io.*;
class Book {
int id;
String name;
public Book(int id, String name) {
this.id = id;
this.name = name;
}
}
public class LinkedListSnippets {
public static void main( String []args) {
LinkedList<Book> list = new LinkedList<Book>();
Book b1 = new Book(1, "To kill a mocking bird");
Book b2 = new Book(2, "Java for Beginners");
list.add(b1);
list.add(1, b2);
list.addFirst(new Book(0, "addFirst"));
list.addLast(new Book(list.size(), "addLast"));
LinkedList<Book> cloneList = (LinkedList<Book>) list.clone();
cloneList.remove(); //removing addFirst
cloneList.remove(b2); //removing Java for Beginners
cloneList.removeLast(); //removing addLast
for(Book b: list)
System.out.println(b.id + " " + b.name);
System.out.println("---------------");
System.out.println("CLONE");
System.out.println("---------------");
for(Book b: cloneList)
System.out.println(b.id + " " + b.name);
System.out.println("---------------");
Book arrOfBooks[] = new Book[list.size()];
arrOfBooks = list.toArray(arrOfBooks);
for(Book b: arrOfBooks)
System.out.println(b.id + " " + b.name);
}
}
/*
OUTPUT:
0 addFirst
1 To kill a mocking bird
2 Java for Beginners
3 addLast
---------------
CLONE
---------------
1 To kill a mocking bird
---------------
0 addFirst
1 To kill a mocking bird
2 Java for Beginners
3 addLast
*/
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.