Web | This Site

Java Basics Examples
Java Tutorial
Java Useful Resources
Selected Reading
© 2011 TutorialsPoint.COM

| Home |  | References |  | Discussion Forums |  | About TP

# Java Examples - Adding Element to Linked List

## Problem Description:

How to add an element at first and last position of a linked list?

## Solution:

Following example shows how to add an element at the first and last position of a linked list by using addFirst() and addLast() method of Linked List class.

    import java.util.LinkedList;

    public class Main {
       public static void main(String[] args) {
          LinkedList lList = new LinkedList();
          lList.add("1");
          lList.add("2");
          lList.add("3");
          lList.add("4");
          lList.add("5");
          System.out.println(lList);
          lList.addFirst("0");
          System.out.println(lList);
          lList.addLast("6");
          System.out.println(lList);
       }
    }

## Result:

The above code sample will produce the following result.

    1, 2, 3, 4, 5
    0, 1, 2, 3, 4, 5
    0, 1, 2, 3, 4, 5, 6

Advertisement

Online Image Processing

Indian Baby Names