Difference Between Java Enumeration and Iterator by amitkumar88265@gmail.com (#12844)
* added Enumertion and Iterator code example * formatted the code * formatted the code * move code examples to other modules * corrected the pkg name * corrected the pkg name * fixed compile time issue Co-authored-by: Amit Kumatr <amit.kumar@fyndna.com>
This commit is contained in:
parent
e460a10c6d
commit
63058bc24c
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.enumerationiteratordifferences;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public final class DataUtil {
|
||||
|
||||
private DataUtil() {
|
||||
}
|
||||
|
||||
static List<Person> getPersons() {
|
||||
Person person1 = new Person("amit", "kumar");
|
||||
Person person2 = new Person("yogi", "kuki");
|
||||
Person person3 = new Person("raj", "dosi");
|
||||
Person person4 = new Person("prakash", "kumar");
|
||||
return Arrays.asList(person1, person2, person3, person4);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.enumerationiteratordifferences;
|
||||
|
||||
import java.util.Enumeration;
|
||||
import java.util.Vector;
|
||||
|
||||
import static com.baeldung.enumerationiteratordifferences.DataUtil.getPersons;
|
||||
|
||||
public class EnumerationExample {
|
||||
public static void main(String[] args) {
|
||||
|
||||
Vector<Person> people = new Vector<>(getPersons());
|
||||
Enumeration<Person> enumeration = people.elements();
|
||||
while (enumeration.hasMoreElements()) {
|
||||
System.out.println("First Name = " + enumeration.nextElement()
|
||||
.getFirstName());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.enumerationiteratordifferences;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import static com.baeldung.enumerationiteratordifferences.DataUtil.getPersons;
|
||||
|
||||
public class IteratorExample {
|
||||
public static void main(String[] args) {
|
||||
List<Person> persons = getPersons();
|
||||
Iterator<Person> iterator = persons.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
System.out.println("First Name = " + iterator.next()
|
||||
.getFirstName());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.enumerationiteratordifferences;
|
||||
|
||||
public class Person {
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public Person(String firstName, String lastName) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue