开发者

Storing an Iterator Reference

开发者 https://www.devze.com 2023-03-23 09:28 出处:网络
I have a Linked List that holds contact information(name, date of birth, etc...). I add the contacts in the list into the List. I want to use the iterator 开发者_运维百科to go through the list so that

I have a Linked List that holds contact information(name, date of birth, etc...). I add the contacts in the list into the List. I want to use the iterator 开发者_运维百科to go through the list so that I can access all the contacts' information. This is where I have the problem. I use a Next button to access all the contacts' information but I am doing it using indexes which increment every time I press Next. I don't want to do it using increments but rather with iterator. When I use the iterator I try to save the reference but I think i'm doing it wrong.

btnNext.addActionListener(new ActionListener() {

        private ContactList save;

public void actionPerformed(ActionEvent arg0) {

Iterator<ContactList> iterator = list.iterator();

if(iterator.hasNext())
{
save = itr.next();
name.setText(save.firstName);
lastName.setText(save.lastName);
dob.setText(save.dob);
homeNum.setText(save.homeNum);
cellNum.setText(save.cellNum);
            }
 }
 }};

I Know that this code only gets the first contact from the list. I want the code to get the next contact if the button is also pressed but i know that since the iterator is in the action handling that it doesn't save the itr.next(), if i try to move the iterator and put it with the other fields then I get a ConcurrentModualError. Any help would be appreciated.


You're close, but you're not actually saving the iterator.

btnNext.addActionListener(new ActionListener() {

    // save the iterator, not the list item
    private Iterator<ContactList> iterator;

    public void actionPerformed(ActionEvent arg0) {

        if(iterator == null){
            iterator = list.iterator();
        }

        if(iterator.hasNext())
        {
            ContactList save = iterator.next(); // first time itr is mentioned, assume you mean iterator
            name.setText(save.firstName);
            lastName.setText(save.lastName);
            dob.setText(save.dob);
            homeNum.setText(save.homeNum);
            cellNum.setText(save.cellNum);
        }
     }
 }};

The tricky part here is that every call to list.iterator() gets a new iterator, so your code was starting at the beginning every time. You want your ActionListener to save the Iterator the first time you get it, and then keep using it each time after that.


Your error is actually a ConcurrentModificationException. With a LinkedList, you can't iterate it with an Iterator at the same time that changes are being made to it. By storing the Iterator long-term like that, you're basically guaranteeing it will happen. The simplest approach would be just to store the index of the list you're currently viewing and make your buttons change the index.

0

精彩评论

暂无评论...
验证码 换一张
取 消