Advertisement
Methods | Description |
---|---|
boolean hasNext() | Returns true if there are more elements in a collection, otherwise it returns false. |
E next() | Returns the next element in a collection. |
void remove() | Removes the current element from a collection. |
import java.util.*;
class IteratorDemo
{
public static void main(String... ar)
{
ArrayList<String> arr= new ArrayList<String>();
arr.add("C");
arr.add("A");
arr.add("4");
arr.add("F");
arr.add("x");
arr.add("1");
Iterator itr = arr.iterator();
System.out.println("Iterating over the collection using iterator() method ");
System.out.print("Contents of ArrayList are : ");
while(itr.hasNext())
{
System.out.print(itr.next() + " " );
}
System.out.println();
System.out.println("Size of arraylist = "+ arr.size());
}
}
Iterating over the collection using iterator() method
Contents of ArrayList are : C A 4 F x 1
Size of arraylist = 6
Advertisement
import java.util.*;
class IteratorDemo2
{
public static void main(String... ar)
{
ArrayList<Integer> arr= new ArrayList>Integer>();
arr.add(10);
arr.add(30);
arr.add(5);
arr.add(40);
arr.add(15);
arr.add(50);
System.out.print("Contents of ArrayList are : ");
System.out.println(arr);
//Obtaining an Iterator to the start of this collection class.
Iterator<Integer> itr = arr.iterator();
System.out.println("Removing element 40 from ArraylList");
while(itr.hasNext())
{
int element =itr.next();
if(element==40)
{
itr.remove();
}
}
System.out.print("Contents of ArrayList are : ");
System.out.println(arr);
System.out.println("Size of arraylist after removing an element = "+ arr.size());
}
}
Contents of ArrayList are : [10, 30, 5, 40, 15, 50]
Removing element 40 from ArraylList
Contents of ArrayList are : [10, 30, 5, 15, 50]
Size of arraylist after removing an element = 5
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement