最好的实践和解决方案是检查"索引"以下解决方案的工作,但感觉很骇人听闻。有更好的选择吗?
public void nextPerson(int index){ //Index is the current location in the arraylist
try{
System.out.println(thePeople.get(index++));
}
catch (IndexOutOfBoundsException e){
System.out.println("At the end");
}
}
我通过拥有一个局部变量来跟踪ArrayList索引来弄清楚。相反,我能够有两种方法来处理移动的阵列列表。一个用于输出的当前位置。
if(arrayPosition < thePeople.size() - 1)
编辑:java是通过value。这意味着,如果将"索引"变量传递给函数,则外部变量不会受到函数内部执行的更改的影响。
在public void nextPerson(){
if (index>=0 && index<thePeople.size())
System.out.println(thePeople.get(index++));
} else {
System.out.println("At the end");
}
}
或通过它并返回
public int nextPerson(int index){
if (index>=0 && index<thePeople.size())
System.out.println(thePeople.get(index++));
} else {
System.out.println("At the end");
}
return index;
}
对于Previouperson而言,只需使用index--
;
顺便说一句,如果将索引保留在消费类中,则在此对象之外,您可以在消费者类中获取整个列表并迭代其...