Series

Iterator [Java] LinkedList<String> animals - for, while

More Code 2018. 6. 16. 04:47


// Java : Iterator

package iteration;

import java.util.LinkedList;
import java.util.Iterator;

public class Program {

public static void main(String[] args) {
LinkedList<String> animals = new LinkedList<String>();
animals.add("dog");
animals.add("cat");
animals.add("fox");

for (String animal : animals) {
System.out.println(animal);
}

// Iterator class
// hasNext(): Returns true if there is at least one more element;
// otherwise, it returns false.
// next(): Returns the next object and advances the iterator.
// remove(): Removes the last object that was returned by next from
// the collection.
Iterator<String> it = animals.iterator();
while (it.hasNext()) {
String animal = it.next();
System.out.println(animal);
}
}
}