Java LinkedList element() Method
Example
Get the first item in a list:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
System.out.println(cars.element());
System.out.println(cars);
}
}
Definition and Usage
The element() method returns the first item in the list. It does not remove the item.
It works like getFirst(). If the list is empty, it throws a NoSuchElementException.
Tip: Use the peek() method if the list can be empty. It returns null instead of throwing an exception.
Syntax
public T element()
T refers to the data type of items in the list.
Parameter Values
None.
Technical Details
| Returns: | The first item in the list. |
|---|---|
| Throws: | NoSuchElementException - if the list is empty. |
Related Pages
❮ LinkedList Methods