Skip to content

Instantly share code, notes, and snippets.

@fahmifan
Created November 21, 2018 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fahmifan/1f1b1b044faf5d0a4f8c18f0aade4dd6 to your computer and use it in GitHub Desktop.
Save fahmifan/1f1b1b044faf5d0a4f8c18f0aade4dd6 to your computer and use it in GitHub Desktop.
example use of Iterator type in java language
import java.util.*;
// Try compile with `javac` & `javac -Xlint`
class TryIterator {
public static void main(String args[]) {
// create an array list
ArrayList<String> al = new ArrayList();
// add elements to the array list
al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F");
// to print all Element use `for each`
System.out.println("Original contents (foreach): ");
// it reads, for every `String it` in List `al`
for(String it: al) {
System.out.print(it);
}
System.out.println("");
// foreach is same as iterator
// use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while (itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
// add enter
System.out.println();
// litr saved the refference memory (pointer) to `al` object
// modify objects being iterated
ListIterator litr = al.listIterator();
while (litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while (itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
// enter
System.out.println();
// now, display the list backwards
System.out.print("Modified list backwards: ");
while (litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment