我有一些問題我有兩個類,每個都返回一個Iterator,還有一個類返回名爲Student的值。有了這段代碼,我可以迭代一個類,我想知道是否有一種方法可以在另一個類上迭代而不需要在我的Machine類中添加第二個類。這裏是我的代碼看起來是這樣的:只用一個迭代器迭代兩個列表Java
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());
}
}
}
我會去教室1去見珍妮弗洛佩茲:) 此外,你應該在循環中使用兩個迭代器。 – vulkanino 2012-03-01 16:24:47
你真的需要使用迭代器嗎? – hurtledown 2012-03-01 16:25:20
我不太明白。你不必有一個內部循環,但你需要有另一個迭代器。你可以編輯你的問題,提供更多關於你在循環中試圖做什麼的信息嗎? – Gray 2012-03-01 16:28:28