LinkedList Iterators Get Elements Java

LinkedList Iterators Get Elements Java

In this program, different styles of retrieving the elements and also extracting a few elements from the list are shown.

Example on LinkedList Iterators Get Elements Java

Output screenshot on LinkedList Iterators Get Elements Java

A generics linked list object myList is created that stores strings only. With add() method, inherited from Collection interface, a few strings are added.

The above for loop is a modified form of basic for loop (generally in other languages known as foreach) and was introduced with JDK 1.5. The working of this enhanced for loop is discussed very clearly in “Collections Enhanced for loop (foreach)“.

The Iterator (equivalent to Enumeration) interface is used to print the elements of the linked list. The methods hasNext() and next() are illustrated elaborately in “Iterator Interface“.

Another generics linked list object yourList is created without any elements. All the elements of myList are added at a time with addAll() method inherited from Collection interface.

Using ListIterator object it2 all the elements of the linked list from 2nd element are printed. The ListIterator is capable to print in reverse order and is shown in “ListIterator Interface“.

The comparison of Iterator and ListIterator is shown in “Iterator vs ListIterator“.

subList() method, inherited from List interface, is used to extract a few elements (1, 2, 3 and 4) of myList and are made another list ourList. Like this, from one list, we can make a number of lists with our choicest elements.

Leave a Reply

Your email address will not be published. Required fields are marked *