Collection Continued - Notes Lyst5117
Collection Continued - Notes Lyst5117
It is clear from previous sessions that values in both these framework have
indexes, so indexes can be accessed using for loop. But let’s be sure about it
by actually seeing the output
Output:
Now let’s see for LinkedList
Output:
But that’s not the case with other frameworks as they don’t have indexes
assigned to the values stored in them. So let’s see how to access them
The Java for-each loop or enhanced for loop is introduced since J2SE 5.0. It
provides an alternative approach to traverse the array or collection in Java. It
is mainly used to traverse the array or collection elements. The advantage of
the for-each loop is that it eliminates the possibility of bugs and makes the
code more readable. It is known as the for-each loop because it traverses each
element one by one.
The drawback of the enhanced for loop is that it cannot traverse the elements
in reverse order.
Here, you do not have the option to skip any element because it does not
work on an index basis. Moreover, you cannot traverse the odd or even
elements only.
But, it is recommended to use the Java for-each loop for traversing the
elements of array and collection because it makes the code readable.
Output:
Let us now see the next method to access the values.
Iterator
Iterator vs ListIterator:
Using ListIterator, we can traverse a List in both the directions (forward and
Backward).
We can obtain indexes at any point of time while traversing a list using
ListIterator. The methods nextIndex() and previousIndex() are used for this
purpose.
We can add element at any point of time while traversing a list using
ListIterator.
5) We cannot replace the existing element value when using Iterator.
6) Methods of Iterator:
hasNext()
next()
remove()
Methods of ListIterator:
add(E e)
hasNext()
hasPrevious()
next()
nextIndex()
previous()
previousIndex()
remove()
set(E e)