Professional Documents
Culture Documents
Methods in Iterator Interface
Methods in Iterator Interface
Methods in Iterator Interface
Method Description
boolean hasNext() Checks if the iterator has more
elements to traverse
E next() Moves the iterator to next element
and returns that element
void remove() Removes the last visited element from
underlying container class
Note:next() should have been called
before calling remove() else will throw
IllegalStateException
Method Description
boolean hasPrevious() Checks if the iterator has more
elements to traverse in reverse
direction
E previous() Moves the iterator to next element
and returns that element in reverse
direction
int nextIndex() Returns the index of the next element
in the iteration in forward direction
int previousIndex() Returns the index of the next element
in the iteration in reverse direction
void set(Element) Sets the last element visited (using
next or previous) .It replaces the
existing element
Collections.sort(lst);
System.out.println("After Sorting");
System.out.println(lst);
lst.clear();
lst.add("Rajashekar");
lst.add("Suresh");
lst.add("Sudhakar");
lst.add("Vishnu");
lst.add("Aakash");
System.out.println("Before Sorting");
Collections.sort(lst);
System.out.println("After Sorting");
System.out.println(lst);
Collections.shuffle(lst);
System.out.println("After shuffling");
System.out.println(lst);
Before Sorting
[10, 25, 15, 12]
After Sorting
[10, 12, 15, 25]
Before Sorting
After Sorting
[Aakash, Rajashekar, Sudhakar, Suresh, Vishnu]
After shuffling
[Rajashekar, Aakash, Vishnu, Suresh, Sudhakar]
LinkedList is combination of both list & queue
When you want add or remove elements frequently we can use LinkedList
`Interview Question:
Note:LinkedList implements both interfaces List & DeQueue(It should act as both List as well as
Queue)
package com.qspiders.collectionsdemo;
import java.util.LinkedList;
import java.util.ListIterator;
lst.addFirst("Hello");
System.out.println(lst);
lst.addLast("Bangalore");
ListIterator litr=lst.listIterator();
System.out.println("Using ListIterator");
System.out.println("Using hasNext()");
while(litr.hasNext())
{
System.out.println(litr.next());
}
System.out.println("Using hasPrevious()");
while(litr.hasPrevious())
{
System.out.println(litr.previous());
}