0

I have coded the following to add elements to the empty list using the ListIterator:

ArrayList<String> list = new ArrayList<String>();
ListIterator<String> listIterator = list.listIterator();

public void append(String... tokens) {

        if(tokens == null)
            return;

        // append tokens at the end of the stream using the list iterator
        for(int i = 0 ; i < tokens.length ; ++i){

            // if the token is not null we append it 
            if(tokens[i] != null && !tokens[i].equals(""))
                listIterator.add(tokens[i]);
        }

        reset();
    }

I want to add elements to this empty list using the listIterator and then after adding all the elements I want to move the iterator to the beginning of the list and I also want to be able to remove the elements where the iterator points, for some reason my method doesn't seem to work, kindly help.

2 Answers 2

2

Perhaps I'm not understanding your problem, but it seems like you really want to have...

list.add(tokens[i]);

instead of...

listIterator.add(tokens[i]);
Sign up to request clarification or add additional context in comments.

2 Comments

I actually want to add elements to the iterator using listIterator to avoid the ConcurrentModificationException , that is why I am using a listIterator
Could you be more specific about what's not working? One possible bug (perhaps it's intended) is ++i instead of i++.
0

After you are done adding items to the iterator, get new instance of the iterator and start again. What is the reset() method supposed to do?

You will not get a ConcurrentModificationException unless you modify the list you are looping through.

Maybe this is what you are looking for.

    ArrayList<String> list = new ArrayList<String>();
    ListIterator<String> listIterator = list.listIterator();
    String[] tokens = {"test", "test1", "test2"};

    // append tokens at the end of the stream using the list iterator
    for (int i = 0; i < tokens.length; ++i) {

        // if the token is not null we append it
        if (tokens[i] != null && !tokens[i].equals(""))
            listIterator.add(tokens[i]);
    }

    while (listIterator.hasPrevious()) {
        if(listIterator.previous().toString().equals("test1")) {
            listIterator.remove();
        }
    }

    while (listIterator.hasNext()) {
        System.out.println(listIterator.next().toString());
    }

3 Comments

The reset method is used to set the iterator to the beginning of the list
Does it return a new iterator? How are you resetting it?
while(listIterator.hasPrevious())listIterator.previous();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.