I'm having some problems I have two classes and each one returns a Iterator, there is a class that return the values named Student. With this code I can iterate over one class and I'd like to know if there is a way to iterate over the other class without adding a second while at my Machine class. Here is how my code looks like:
import java.util.*;
import java.lang.reflect.*;
class ClassRoom1{
ArrayList<Student> al = new ArrayList<Student>();
Student st;
public ClassRoom1(){
st = new Student("Michael", "Smith", 12);
al.add(st);
st = new Student("Jennifer", "Lopez", 13);
al.add(st);
}
public void addStudent(String name, String lastName, int age) {
Student st = new Student(name, lastName, age);
al.add(st);
}
public ArrayList getStudents(){
return al;
}
public Iterator returnIter(){
Iterator iter = getStudents().iterator();
return iter;
}
}
class ClassRoom2{
ArrayList<Student> al = new ArrayList<Student>();
Student st;
public ClassRoom2(){
st = new Student("Brian", "Con", 15);
al.add(st);
st = new Student("Megan", "Bell", 15);
al.add(st);
}
public void addStudent(String name, String lastName, int age) {
Student st = new Student(name, lastName, age);
al.add(st);
}
public ArrayList getStudents(){
return al;
}
public Iterator returnIter(){
Iterator iter = getStudents().iterator();
return iter;
}
}
public class Machine{
Student st;
ClassRoom1 clrm1 = new ClassRoom1();
ClassRoom2 clrm2 = new ClassRoom2();
public static void main(String[] args){
Machine mch = new Machine();
ArrayList al = new ArrayList();
Iterator iter = al.iterator();
mch.printStudens(iter);
}
void printStudens(Iterator iter){
iter = clrm1.returnIter();
while(iter.hasNext()){
st = (Student) iter.next();
System.out.println("\nName: " + st.getName() + "\nLast name: " + st.getLastName() + "\nAge: " + st.getAge());
}
}
}
First of all, instead of code duplication, use OO:
Then
clrm1
andclrm2
are objects of ClassRoom. You can actually hold arbitrary many ClassRoom objects in an own list and do nested iterations, firstly over all ClassRooms, within which you iterate over all Students in the current ClassRoom.Update:
If you once need to combine iterators (no necessity here), I'd either write my own little concatenating iterator which, e.g. sequencially, iterates over the iterators it holds, or use Guava's
Iterator.concat()
, which "Combines multiple iterators into a single iterator". Either way, you wouldn't have to duplicate any data.