Monday, November 19, 2007

How to create a Linked List

This Java tip illustrates a method of creating a List. The tip here describes various aspects of linked list such as adding an element in a list, retrieving an element and removing an element from the list.

// Create a link list
List list = new LinkedList(); // Doubly-linked list
list = new ArrayList(); // List implemented as growable array

// Append an element to the list

// Insert an element at the head (0) of the list
list.add(0, "b");

// Get the number of elements in the list
int size = list.size(); // 2

// Retrieving the element at the end of the list
Object element = list.get(list.size()-1); // a

// Retrieving the element at the head of the list
element = list.get(0); // b

// Deleting occurrance of the first element of the link list
boolean b = list.remove("b"); // true
b = list.remove("b"); // false

// Remove the element at a particular index
element = list.remove(0); // a

No comments: