Java Collection Programs

LinkedList add items

In this chapter, our task is:

  • we will create a LinkedList
  • We will add few elements in LinkedList.
  • Print the list

Example: Add elements to Linkedlist in java

package javaRadarLinkedList;

import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedList;

public class EnumerationTraversal {

       public static void main(String[] args) {

         //create Linked List
          LinkedList javaRadarList = new LinkedList();

         //Add elements to LinkedList
           //print the list



[Java, Jquery, Spring, Hibernate, EJB]



Use Generics in LinkedList

We can apply Generics on the LinkedList to restric the type of object that the Vector supports.

For example, 

LinkedList<Integer> javaRadarList= new LinkedList<Integer>();


Once you replace ⇒ LinkedList  javaRadarListnew LinkedList(); with above:

  • You will be able to add only Integer objects in the created LinkedList 'javaRadarList
  • If you add object of other type like Integer, Float, etc, you will get compiler error.

You can have any object type like String, Float, etc as Generics in place of Integer.

*Its your task to play with other object types in the example. Please practice and revert back in case of any problem.


package javaRadarLinkedList;

import java.util.LinkedList;

public class SimpleLinkedList {

      public static void main(String[] args) {

            //create Linked List
            LinkedList javaRadarList = new LinkedList();

            //Add elements to LinkedList
            //print list




[101, 107, 210, 33, 87]
Point to note:
We see we are inserting int data type like 101, 107, 210, 33, 87 etc. in the list.
But list, set takes only objects as element, not primitive data type values like int, float, etc.
How does our code actually work?
During compilation, 101 is automatically converted to Integer Wrapper Class object.
  • We inserted 101 but compiler does this javaRadarList(Integer.valueOf(101));
  • We inserted 107 but compiler does this javaRadarList(Integer.valueOf(107));
  • Similarly all the int is converted to Integer Wrapper class object.

Please Share this page
Views : 108
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!