Following methods are used to get first element in linked list in java:
- element(): Retrieves, but does not remove, the head (first element) of this list.
- getFirst(): Returns the first element in this list.
- peek(): Retrieves, but does not remove, the head (first element) of this list.
- peekFirst(): Retrieves, but does not remove, the first element of this list, or returns null if this list is empty.
Example:
package com.w3schools;
import java.util.LinkedList;
public class Test {
public static void main(String args[]){
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Jai");
linkedList.add("Mahesh");
linkedList.add("Naren");
linkedList.add("Vivek");
linkedList.add("Vishal");
linkedList.add("Hemant");
System.out.println("Actual LinkedList:"+linkedList);
System.out.println("First Element: "+linkedList.element());
System.out.println("First Element: "+linkedList.getFirst());
System.out.println("First Element: "+linkedList.peek());
System.out.println("First Element: "+linkedList.peekFirst());
}
} |
package com.w3schools;
import java.util.LinkedList;
public class Test {
public static void main(String args[]){
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("Jai");
linkedList.add("Mahesh");
linkedList.add("Naren");
linkedList.add("Vivek");
linkedList.add("Vishal");
linkedList.add("Hemant");
System.out.println("Actual LinkedList:"+linkedList);
System.out.println("First Element: "+linkedList.element());
System.out.println("First Element: "+linkedList.getFirst());
System.out.println("First Element: "+linkedList.peek());
System.out.println("First Element: "+linkedList.peekFirst());
}
}
Output
Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
First Element: Jai
First Element: Jai
First Element: Jai
First Element: Jai |
Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
First Element: Jai
First Element: Jai
First Element: Jai
First Element: Jai