Topics Index

LinkedListDemo - Java Example Program

import java.util.*;

class LinkedListDemo
    public static void main(String arg[])
        LinkedList characters = new LinkedList(); // LINE A
        System.out.println("Original list: " + characters);
        characters.add(1, 'B'); // LINE B
        System.out.println("After adding B: " + characters);
        List numbers = new ArrayList(); // LINE C
        characters.addAll(numbers); // LINE D
        System.out.println("After adding numbers: " + characters);
        characters.addFirst("First"); // LINE E
        characters.addLast("Last"); // LINE F
        System.out.println("After adding First and Last: " + characters); // LINE G
        characters.removeFirst(); // LINE H
        characters.removeLast(); // LINE I
        System.out.println("After removing First and Last:" + characters);
        //converting characters to char[] array
        Object[] newCharacters = characters.toArray(); // LINE J
        System.out.println("Conveting LinkedList to Array of objects: ");
        for (Object newCharacter : newCharacters)
            System.out.print(newCharacter + ", ");

Original list: [A, C, D]
After adding B: [A, B, C, D]
After adding numbers: [A, B, C, D, 1, 2, 3]
After adding First and Last: [First, A, B, C, D, 1, 2, 3, Last]
After removing First and Last:[A, B, C, D, 1, 2, 3]
Conveting LinkedList to Array of objects:
A, B, C, D, 1, 2, 3,


At LINE A we have created a LinkedList and added elements to it. At LINE B we have we have added character B to the characters. At LINE C we have created an ArrayList and added numbers to it. At LINE D we have added all the numbers to the end of the characters using addAll method and displayed. At LINE E and LINE F we have added First and Last using addFirst and addLast and displayed it at LINE G. At LINE H and LINE I we have removed First and Last from the list using removeFirst and removeLast methods. At LINE J we have converted characters to array of Objects and printed them using a for-Each loop.

  • To add numbers to the first of characters replace LINE D with the code below.
    addAll(0, numbers)
  • Replace LINE H and LINE I with the below lines of code.
    since both have the same functionality we don't see any change in the output.
  • Replace LINE J with the code below
    char[] newCharacters = characters.toArray();
    The above line throws a compilation error since objects cannot be converted to primitive data type char.

© meritcampus 2019

All Rights Reserved.

Open In App