SUBSCRIBE HERE TO GET POST UPDATES VIA EMAIL :

Delivered by FeedBurner

LinkedList In Java

  • LinkedList class extends AbstractList class.
  • LinkedList class implements List and Deque interfaces.
  • LinkedList class is using doubly linked list to store elements in list.
  • LinkedList can hold duplicate elements in list.
  • LinkedList is non synchronized.
  • Manipulation is faster in linkedlist as shifting is not required when new element is inserted or deleted from list.
  • You can use it as list, stack or queue as it implements List and Deque interfaces of collection framework.
LinkedList Hierarchy

LinkedList hierarchy in java

Bellow given example will show you usage of different methods of linkedlist class in java.

LinkedListExample
package JAVAExamples;

import java.util.LinkedList;

public class LinkedListExample {
 public static void main(String args[]) {
  // Prepare linkedlist.
  LinkedList lst = new LinkedList();
  // Add elements using add method.
  lst.add("one");
  lst.add("two");
  lst.add("three");
  lst.add("four");
  lst.add("five");
  lst.add("six");
  // Add element at first position in list using addFirst.
  lst.addFirst("FirstNumber");
  // Add element at last position in list using addLast.
  lst.addLast("LastNumber");
  // Add elements at index 1 in list.
  lst.add(1, "1 number");
  System.out.println("List items : " + lst);

  // Removing first item from list using removeFirst method.
  lst.removeFirst();
  System.out.println();
  System.out.println("List items after removing first item from list: "+ lst);

  // Removing last item from list using removeLast method.
  lst.removeLast();
  System.out.println();
  System.out.println("List items after removing last item from list : "+ lst);

  // Removing item from list using value.
  lst.remove("two");
  System.out.println();
  System.out.println("List items after removing item by value from list : "+ lst);

  // Removing item from list using index.
  lst.remove(3);
  System.out.println();
  System.out.println("List items after removing item by index from list : "+ lst);

  // Get item from list using index.
  System.out.println();
  System.out.println("List item at index 2 is : " + lst.get(2));

  // Set item at given index in list.
  lst.set(2, "Newset Value");
  System.out.println();
  System.out.println("List items after set(replace) new value at index 2 in list : "+ lst);
 }
}

No comments:

Post a Comment