Reputation: 15
Im making a simple app with swing and i'm new when it comes to arraylists and listiterator. What i'm trying to do is a button that allows you to update information about people in an arraylist. Im supposed to do this without the use of for or for-each loops. Here's my code:
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);
}
}
This code works, but it looks weird. Do i have to jump back and fourth like that (listIt.next() and then listIt.previous()) or is there a better way?
//N
Upvotes: 0
Views: 45
Reputation: 46960
The normal idiom using the old iterator syntax would be:
Iterator<Student> studentIterator = peopleArray.iterator();
while(studentIterator.hasNext()){
Student student = studentIterator.next();
// Do stuff with student. For example:
if(student.getFirstName().equalsIgnoreCase(firstname)) {
// ...
}
}
Upvotes: 1
Reputation: 27373
You don't havwe to jumpt forth and back, make sure only call next() once. What about this:
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);
}
}
Upvotes: 2