How to Retrieve Items from a LinkedList in Java - dummies

How to Retrieve Items from a LinkedList in Java

By Doug Lowe

As with the ArrayList class, you can use the get method to retrieve an item in Java based on its index. If you pass it an invalid index number, the get method throws the unchecked IndexOutOfBoundsException.

You can also use an enhanced for loop to retrieve all the items in the linked list. The examples use this enhanced for loop to print the contents of the officers linked list:

for (String s : officers)
 System.out.println(s);

If you want, you can also use the iterator method to get an iterator that can access the list.

The LinkedList class also has a variety of other methods that retrieve items from the list. Some of these methods remove the items as they are retrieved; some throw exceptions if the list is empty; others return null.

Nine methods retrieve the first item in the list:

  • getFirst: Retrieves the first item from the list. This method doesn’t delete the item. If the list is empty, NoSuchElement-Exception is thrown.

  • element: Identical to the getFirst method. This strangely named method exists because it’s defined by the Queue interface, and the LinkedList class implements Queue.

  • peek: Similar to getFirst but doesn’t throw an exception if the list is empty. Instead, it just returns null. (The Queue interface also defines this method.)

  • peekFirst: Identical to peek. Only the name of the method is changed to protect the innocent.

  • remove: Similar to getFirst but also removes the item from the list. If the list is empty, it throws NoSuchElementException.

  • removeFirst: Identical to remove. If the list is empty, it throws NoSuchElementException.

  • poll: Similar to removeFirst but returns null if the list is empty. (This method is yet another method that the Queue interface defines.)

  • pollFirst: Identical to poll (well, identical except for the name of the method).

  • pop: Identical to removeFirst (but with a catchier name).

Four methods also retrieve the last item in the list:

  • getLast: Retrieves the last item from the list. This method doesn’t delete the item. If the list is empty, NoSuchElement-Exception is thrown.

  • peekLast: Similar to getLast but doesn’t throw an exception if the list is empty. Instead, it just returns null.

  • removeLast: Similar to getLast but also removes the item. If the list is empty, it throws NoSuchElementException.

  • pollLast: Similar to removeLast but returns null if the list is empty.