Archives for 

List

Classes that implements the List interface directly or indirectly were described in this category

LinkedList in Java

LinkedList implements List interface in collections frame work of Java.In LinkedList the items stored is based on indexing and those are doubly linked with each other.Insertion and deletion are faster in LinkedList when compared with ArrayList.But iteration is slower when compared with ArrayList.Now let us see an example.The example adds few strings to the LinkedList object.Then displaying each item. Finally removing all items from the list.

import java.util.LinkedList;
import java.util.List;
public class LinkedListSample {
private List list = null;
public LinkedListSample(){
list = new LinkedList();
}
public void addItemsToList() {
String[] listItems = {"dog", "cat", "cow", "elephant", "sheep"};
for (int i = 0; i < listItems.length; i++) { list.add(listItems[i]); } } public void displayList() { System.out.println("Displaying contents of list"); for (String item : list) { System.out.println("Item = " + item); } } public void removeItems() { System.out.println("Removing contents of list"); list.remove("dog"); list.remove("cat"); list.remove("cow"); list.remove("elephant"); list.remove("sheep"); System.out.println("Contents removed ,now size of list = " + list.size()); } public static void main(String[] args) { LinkedListSample sample = new LinkedListSample(); sample.addItemsToList(); sample.displayList(); sample.removeItems(); } }

Now let us see the output.

Output

Displaying contents of list

Item = dog

Item = cat

Item = cow

Item = elephant

Item = sheep

Removing contents of list

Contents removed  ,now size of list = 0

LinkedList Vs ArrayList

Both implements the List interface.ArrayList is based on index but it is not sorted.LinkedList is also based on index ,but items in LinkedList are doubly linked to each other.Iteration is faster in ArrayList.Deletion and insertion are faster in LinkedList. ArrayList implements the marker interface 'RandomAccess', but LinkedList is not implementing it.LinkedList implements Queue interface (from Java 5 onwards). But ArrayList is not implementing Queue interface.