Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

java - What does List Iterator's add() method do to the iterator?

I want to be able to insert elements to the ArrayList<String> using ListIterator, but somehow I am confused even after reading the documentation related to the add method of the ListIterator class, if I do something like this

for(int i = 0 ; i < list.size() ; ++i)
   listIterator.add( list.get(i) );

What does this code snippet do to my list iterator, where does it move the list iterator?

When I run the following code I get the result as "Hi" -:

import java.util.ArrayList;
import java.util.ListIterator;

public class ListIter {
    public static void main(String[] args) {

        String[] s = {"Hi", "I", "am", "Ankit"};

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

        for (int i = 0; i < s.length; ++i) {
            listIterator.add(s[i]);
        }

        while (listIterator.hasPrevious()) {
            listIterator.previous();
        }

        System.out.println(listIterator.next());
    }
}

Kindly tell how is this output being generated?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not using iterator properly. The correct way using iterators is traverse the list with the iterator itself rather than by index.

ListIterator<SomeObject> listIterator = list.listIterator();

while(listIterator.hasNext()){
  SomeObject o = listIterator.next();
  listIterator.add(new SomeObject());
}

Read the ListIterator#add()

A simple example:

public static void main(String args []){      
        List<String> list= new ArrayList<String>();
        list.add("hi");
        list.add("whats up");
        list.add("how are you");
        list.add("bye");

        ListIterator<String> iterator = list.listIterator();
        int i=0;
        while(iterator.hasNext()){
            iterator.next();
            iterator.add(Integer.toString(i++));                
        }

        System.out.println(list);
        //output: [hi, 0, whats up, 1, how are you, 2, bye, 3]

    }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...