0

The last part of this program should be adding the pickles item between the lettuce and chicken item, but whenever I run it it adds it to the end of the list. I have no idea why. Is this a problem with the way I'm outputting it? I honestly have no idea why this is happening. Please help!

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

List<String> myLinkedList = new LinkedList<String>();

String strOutput="";

myLinkedList.add("Bread1");
myLinkedList.add("mustard");
myLinkedList.add("lettuce");
myLinkedList.add("chicken");
myLinkedList.add("tomato");
myLinkedList.add("Bread2");

ListIterator<String> lit = myLinkedList.listIterator();
while(lit.hasNext()) 
{
  strOutput +=(lit.next() + ", ");
}
strOutput +=("end...\n");    


while(lit.hasPrevious()) 
{
  strOutput +=(lit.previous() + ", ");
}
strOutput +=("end...\n");


lit.next();
lit.next();
lit.next();

myLinkedList.add("pickles");

ListIterator<String> lit2 = myLinkedList.listIterator();

while(lit2.hasNext()) 
{
  strOutput +=(lit2.next() + ", ");
}
strOutput +=("end...\n");    

javax.swing.JOptionPane.showMessageDialog(null, strOutput);
System.exit(0);
  }

} 

2 Answers 2

2

Your list is separate from the iterator in the sense that the state of the iterator isn't reflected in the list itself. To add something using the iterator, use the add method of the iterator.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that is the source of my confusion! Thank you very much!
0

myLinkedList.add("pickles"); will always add it in the end. It doesnot matter where the iterator is. They are both independent.

You should use: myLinedList.add(3,"pickles") to add it between "lettuce" and "chicken"

or

You can use the iterators add method to add it where ever you want. http://docs.oracle.com/javase/7/docs/api/java/util/ListIterator.html#add(E)

1 Comment

That is also a good way to do it! Thanks to all of you for these very good responses! The rest of the program should be a snap.

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.