Collections

how to create a Linked list using the collections API
Previous Home Next

 

In this example we shall see how to create a LinkedList.

In this example we have created a class CollectionExample. For creating a LinkedList we have
to import the java.util package.
 In this example we have created a main method in which we have created a LinkedList object via using the default constructor LinkedList(). Then we added the elements to the list by using the add(Object obj) method to the LinkedList object.

In this example firstly we have created a class named CollectionExample. In this class we have created a LinkedList, then we added the elements to the list by using the add() method on the LinkedList object. Finally, we have displayed the contents of the LinkedList.

 
package r4r.co.in;
import java.util.*;
import java.util.Iterator;
import java.util.List;
import java.util.Collection;



public class CollectionExample {

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub


LinkedList<Object> list=new LinkedList();
list.add(1);
list.add(2);
list.add("r4r");
list.add("shashi");
list.add("s/w engineer");
System.out.println("The contents of the list are as follows: ");
System.out.println(list);


}


}
The output of the above code will be displayed as:

The contents of the list are as follows:
[1, 2, r4r, shashi, s/w engineer]

Previous Home Next