我正在制作一个带有摇摆的简单应用程序,当涉及到arraylists和listiterator时,我是新的。我想要做的是一个按钮,可以让你更新有关arraylist中人物的信息。我应该这样做而不使用for或for-each循环。这是我的代码:
String searchedName = JOptionPane.showInputDialog(null, "Type in the first name of the person you want to update:");
ListIterator<Student> listIt = peopleArray.listIterator();
while(listIt.hasNext()){
String firstname = listIt.next().getFirstname();
if(searchedName.equalsIgnoreCase(firstname){
String newFirstname = JOptionPane.showInputDialog(null, "Input new first name:");
String newLastname = JOptionPane.showInputDialog(null, "Type in new last name:");
String newEmail = JOptionPane.showInputDialog(null, "Type in new email:");
String newOccupation = JOptionPane.showInputDialog(null, "Type in new occupation:");
listIt.previous().setFirstname(newFirstname);
listIt.next().setLastname(newLastname);
listIt.previous().setEmail(newEmail);
listIt.next().setOccupation(newOccupation);
}
}
此代码有效,但看起来很奇怪。我是否必须跳回到第四个(listIt.next()然后listIt.previous())或者有更好的方法吗?
//Ñ
答案 0 :(得分:2)
你不要急于跳起来,确保只调用next()一次。那怎么样:
String searchedName = JOptionPane.showInputDialog(null, "Type in the first name of the person you want to update:");
ListIterator<Student> listIt = peopleArray.listIterator();
while(listIt.hasNext()){
Student studentToUpdate = listIt.next();
if(searchedName.equalsIgnoreCase(studentToUpdate.getFirstname()){
String newFirstname = JOptionPane.showInputDialog(null, "Input new first name:");
String newLastname = JOptionPane.showInputDialog(null, "Type in new last name:");
String newEmail = JOptionPane.showInputDialog(null, "Type in new email:");
String newOccupation = JOptionPane.showInputDialog(null, "Type in new occupation:");
studentToUpdate.setFirstname(newFirstname);
studentToUpdate.next().setLastname(newLastname);
studentToUpdate.setEmail(newEmail);
studentToUpdate.setOccupation(newOccupation);
}
}
答案 1 :(得分:1)
使用旧迭代器语法的正常习语是:
Iterator<Student> studentIterator = peopleArray.iterator();
while(studentIterator.hasNext()){
Student student = studentIterator.next();
// Do stuff with student. For example:
if(student.getFirstName().equalsIgnoreCase(firstname)) {
// ...
}
}