Collections

Linked Lists Java Code With Examples

Table of Contents

Program

import java.io.LinkedList;
import java.util.LinkedList;

public class LinkedListTypes {

	public static void main(String args[]) {

		LinkedList<String> jaswanth = new LinkedList<String>();
		LinkedList<String> venkatesh = new LinkedList<String>();
		LinkedList<String> murugabalan = new LinkedList<String>();
		jaswanth.add("HE");
		jaswanth.add("IS");
		jaswanth.add("FROM");
		jaswanth.add("CHENNAI");
		jaswanth.add("TAMILNADU");
		System.out.println("Jaswanth Is From:" + jaswanth);
		
                //clone()
                venkatesh = (LinkedList) jaswanth.clone();
		murugabalan = (LinkedList) jaswanth.clone();
		System.out.println("Venkatesh Is From:" + venkatesh);
		System.out.println("Murugabalan Is From:" + murugabalan);
		
                //getFirst()
                System.out.println("The first element is: " + jaswanth.getFirst());

                //getLast()
		System.out.println("The Last element is: " + jaswanth.getLast());

                //remove()
		jaswanth.remove();
		System.out.println("Final LinkedList:" + jaswanth);

                // contains​(Object o)
		System.out.println("IS THE LIST CONTAINS CHENNAI : " + jaswanth.contains("CHENNAI"));
	}
}

Output

Jaswanth Is From:[HE, IS, FROM, CHENNAI, TAMILNADU]
Venkatesh Is From:[HE, IS, FROM, CHENNAI, TAMILNADU]
Murugabalan Is From:[HE, IS, FROM, CHENNAI, TAMILNADU]
The first element is: HE
The Last element is: TAMILNADU
Final LinkedList:[IS, FROM, CHENNAI, TAMILNADU]
IS THE LIST CONTAINS CHENNAI : true

Description

public E getFirst()

Returns the first element in this list.

Specified by:

getFirst in interface Deque<E>

Returns:

the first element in this list

Throws:

NoSuchElementException – if this list is empty

public E getLast()

Returns the last element in this list.

Specified by:

getLast in interface Deque<E>

Returns:

the last element in this list

Throws:

NoSuchElementException – if this list is empty

public boolean contains​(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that Objects.equals(o, e).

Specified by:

contains in interface Collection<E>

Specified by:

contains in interface Deque<E>

Specified by:

contains in interface List<E>

Overrides:

contains in class AbstractCollection<E>

Parameters:

o – element whose presence in this list is to be tested

Returns:

true if this list contains the specified element

public E remove()

Retrieves and removes the head (first element) of this list.

Specified by:

remove in interface Deque<E>

Specified by:

remove in interface Queue<E>

Returns:

the head of this list

Throws:

NoSuchElementException – if this list is empty

public Object clone()

Returns a shallow copy of this LinkedList. (The elements themselves are not cloned.)

Overrides:

clone in class Object

Returns:

a shallow copy of this LinkedList instance